TypeScript Beyond the Basics: Unions, Narrowing, Generics and Discriminated Unions
The TypeScript features that make types expressive: union and literal types, narrowing with typeof, instanceof, in and type predicates, discriminated unions with exhaustiveness checks, enums vs literal unions, generic functions and constraints, read-only types, utility types, as const and satisfies.
kvi5hnuCode Sprout team member8 min readOn this page
Article 138 covered annotating values, functions, objects and classes. Real data is messier: a value may be one of several types, functions should work for many types, and states like "loading", "loaded" and "failed" carry different data. This article covers the features that describe such data precisely. They're also the topics that come up most in TypeScript interviews.
Union types
A union type A | B means "an A or a B". Here's a size function that accepts any kind of collection:
function size(collection: unknown[] | Set<unknown> | Map<unknown, unknown>): number {
if (Array.isArray(collection)) {
return collection.length; // here: unknown[]
}
return collection.size; // here: Set or Map, both have size
}
You can only use what all members of a union have in common, until you check which one you have:
function padLeft(value: string, padding: string | number) {
return padding.repeat(2) + value;
}
src3/unions.ts(16,18): error TS2339: Property 'repeat' does not exist on type 'string | number'.
Property 'repeat' does not exist on type 'number'.
T | null and T | undefined are unions too, which is how strict mode tracks values that may be missing.
Narrowing
Inside an if, switch or after an early return, TypeScript narrows a union based on the checks you write. They're ordinary JavaScript checks, so they work at run time as well:

function format(value: string | number | Date | null): string {
if (value === null) return "-";
if (typeof value === "number") return value.toFixed(2);
if (value instanceof Date) return value.toISOString().slice(0, 10);
return value.toUpperCase(); // only string is left
}
Narrowing checks: equality (=== null, === "admin"), typeof (for primitives), instanceof (for classes), Array.isArray, "prop" in obj, and truthiness (if (user) removes null and undefined, but also "" and 0, article 34). For checks TypeScript can't follow, write a type predicate, a function whose return type says what it proves:
function isUser(value: unknown): value is User {
return typeof value === "object" && value !== null && "id" in value && "name" in value;
}
// after `if (isUser(data))`, data is a User
A predicate is only as trustworthy as its implementation, because TypeScript believes it.
Literal types and enums
A literal like "yes" or 3 can itself be a type, and a union of literals describes a fixed set of values:
type Answer = "yes" | "no";
let a: Answer = "yes";
a = "Yes".toLowerCase();
type DieFace = 1 | 2 | 3 | 4 | 5 | 6;
let roll: DieFace = 2 + 3;
src3/unions.ts(21,1): error TS2322: Type 'string' is not assignable to type 'Answer'.
src3/unions.ts(23,5): error TS2322: Type 'number' is not assignable to type 'DieFace'.
The checker doesn't run your calculations: toLowerCase() returns some string, and 2 + 3 some number, so neither is known to fit, even though both results do.
Unions of string literals are the usual way to write enumerations in TypeScript: they cost nothing at run time, autocomplete in editors, and show readable values in logs. TypeScript also has an enum keyword, but it generates run-time code. It's one of the few TypeScript features that isn't just erasable annotations, so Node's type stripping rejects it, as it does namespace and constructor parameter properties. Many teams enable the erasableSyntaxOnly option to forbid these features. When you need the values at run time too, derive the type from a constant array or object:
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
as const makes TypeScript infer the narrowest, read-only type: a tuple of those exact strings instead of string[].
Discriminated unions
The most useful pattern in TypeScript is a union of object types that share a tag property with a different literal value in each member:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number }
| { kind: "triangle"; base: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rect":
return shape.width * shape.height;
default: {
const unhandled: never = shape;
throw new Error(`unknown shape: ${JSON.stringify(unhandled)}`);
}
}
}
src3/shapes.ts(13,13): error TS2322: Type '{ kind: "triangle"; base: number; height: number; }' is not assignable to type 'never'.
Checking shape.kind narrows shape to one member, so shape.radius is only allowed in the circle branch. The default branch is an exhaustiveness check: never is the type with no values, so the assignment only compiles if every member was handled. When someone adds "triangle" to Shape, every switch that forgot it becomes a compile error instead of a silent bug.
Discriminated unions model states precisely: { status: "loading" } | { status: "ok"; data: T } | { status: "error"; error: string } makes "data while still loading" impossible to represent. A common use is a Result type, returned instead of thrown errors. After type erasure it's plain JavaScript:
// The JavaScript that remains after TypeScript erases these types:
// type Result<V, E = Error> = { ok: true; value: V } | { ok: false; error: E };
// function parsePort(text: string): Result<number, string>
// Each object carries an `ok` tag, so callers must check it before using value.
function parsePort(text) {
const n = Number(text);
if (!Number.isInteger(n)) return { ok: false, error: `"${text}" is not a whole number` };
if (n < 1 || n > 65535) return { ok: false, error: `${n} is out of range` };
return { ok: true, value: n };
}
for (const input of ["8080", "http", "70000"]) {
const result = parsePort(input);
if (result.ok) console.log("port", result.value); // TypeScript narrows to the ok: true member
else console.log("error:", result.error);
}
// A discriminated union of shapes; `kind` tells the members apart
const Kind = Object.freeze({ Circle: "circle", Rect: "rect" }); // an "enum" as a plain object
function area(shape) {
switch (shape.kind) {
case Kind.Circle: return Math.PI * shape.radius ** 2;
case Kind.Rect: return shape.width * shape.height;
default: throw new Error(`unhandled shape kind: ${shape.kind}`); // the never case at run time
}
}
console.log(area({ kind: "rect", width: 3, height: 4 }), area({ kind: "circle", radius: 1 }).toFixed(4));
try {
area({ kind: "triangle", base: 2, height: 3 });
} catch (err) {
console.log(err.message);
}
port 8080
error: "http" is not a whole number
error: 70000 is out of range
12 3.1416
unhandled shape kind: triangle
Generics
A generic function has a type parameter, a placeholder filled in at each call, usually inferred from the arguments. It lets one function work for many types without losing type information, which any or unknown would:
function first<T>(items: readonly T[]): T | undefined {
return items[0];
}
const n = first([3, 1, 2]); // number | undefined
const s = first(["a", "b"]); // string | undefined
function longest<T extends { length: number }>(a: T, b: T): T {
return b.length > a.length ? b : a;
}
longest("apple", "fig");
longest([1, 2], [3]);
longest(10, 20);
function zip<A, B>(a: A[], b: B[]): [A | undefined, B | undefined][] {
return Array.from({ length: Math.max(a.length, b.length) }, (_, i) => [a[i], b[i]]);
}
const pairs = zip([1, 2, 3], ["a", "b"]); // [number | undefined, string | undefined][]
src3/generics.ts(12,9): error TS2345: Argument of type 'number' is not assignable to parameter of type '{ length: number; }'.
T extends { length: number }is a constraint:Tcan be any type that has a numericlength, so strings and arrays are accepted and numbers are rejected.- Types can be generic too:
type Result<V, E = Error> = { ok: true; value: V } | { ok: false; error: E }, whereEhas a default. Built-in types likeArray<T>,Promise<T>,Map<K, V>andSet<T>are generic in the same way, and so are classes:class Stack<T> { #items: T[] = []; push(item: T) {...} }.
Read-only types
Parameters marked read-only document, and enforce, that a function doesn't modify its input:
function average(data: readonly number[]): number {
data.sort(); // error: 'sort' does not exist on type 'readonly number[]'
return data.reduce((t, x) => t + x, 0) / data.length;
}
Mutating methods like sort, push and splice simply don't exist on readonly T[] (or ReadonlyArray<T>), and Readonly<T> makes every property of an object type read-only. As with readonly properties, this is a compile-time guarantee only (Object.freeze gives a run-time one). Here the fix is data.toSorted() (article 59), which doesn't modify the array.
Utility types, as const and satisfies
TypeScript can compute new types from existing ones. The built-in utility types cover the common cases:
interface User {
id: number;
name: string;
email: string;
role: "admin" | "editor" | "viewer";
}
type UserPatch = Partial<Omit<User, "id">>; // every field but id, all optional
type UserSummary = Pick<User, "id" | "name">;
type Role = User["role"]; // "admin" | "editor" | "viewer"
type RoleCounts = Record<Role, number>;
function update(user: User, patch: UserPatch): User {
return { ...user, ...patch };
}
const u: User = { id: 1, name: "Ada", email: "ada@example.com", role: "admin" };
update(u, { role: "owner" });
update(u, { id: 2 });
const counts: RoleCounts = { admin: 1, editor: 0 };
src3/utility.ts(17,13): error TS2322: Type '"owner"' is not assignable to type '"admin" | "editor" | "viewer" | undefined'.
src3/utility.ts(18,13): error TS2353: Object literal may only specify known properties, and 'id' does not exist in type 'Partial<Omit<User, "id">>'.
src3/utility.ts(20,7): error TS2741: Property 'viewer' is missing in type '{ admin: number; editor: number; }' but required in type 'RoleCounts'.
| Utility | Produces |
|---|---|
Partial<T> / Required<T> | all properties optional / required |
Readonly<T> | all properties read-only |
Pick<T, K> / Omit<T, K> | only / all but the listed properties |
Record<K, V> | an object with keys K and values V |
ReturnType<F>, Parameters<F>, Awaited<P> | a function's return type, parameter tuple, a promise's result |
NonNullable<T>, Exclude<T, U>, Extract<T, U> | filtered unions |
Deriving types from one source of truth means a change to User updates every related type automatically. T["role"] is an indexed access type, and typeof value in a type position gives a value's type, as used with ROLES earlier.
The satisfies operator checks that a value matches a type without widening the value's own inferred type:
const config = { port: 8080, host: "localhost" } satisfies Record<string, string | number>;
config.port.toFixed(0); // still known to be a number
With an annotation (const config: Record<string, string | number>), config.port would be string | number, and toFixed would be an error.
Going further
- Type definitions for libraries: packages written in TypeScript ship their types; for others, install community definitions, as in
npm install -D @types/node, from the DefinitelyTyped project. - Type assertions (
value as User) tell the checker to trust you. They're unchecked at run time, so prefer narrowing and validation. - Advanced types: conditional types (
T extends string ? A : B), mapped types ({ [K in keyof T]: ... }) and template literal types power library typings, but application code rarely needs them.
Types take effort to learn and to write, but on medium and large projects they catch a remarkable number of bugs before they ship, and they make code easier to change with confidence.
Review quiz
You've finished Part 17: JavaScript Tools and Extensions, and the whole course. Test yourself with the Part 17 review quiz: 20 questions on linting and formatting, testing, npm and semver, bundling and transpiling, JSX and TypeScript.
Then put the whole course together with the final quizzes:
- JavaScript Course Final Exam: 30 questions across all seventeen parts.
- JavaScript Interview Questions: closures,
this, the event loop, coercion and the other favorites. - JavaScript's Delicate Details: spec-level edge cases.
- Modern JavaScript, ES2022 to ES2027: the newest features.
Common questions
When should I use a union vs a generic?
A union describes a value that can be one of a known, fixed set of types. A generic relates types to each other, such as "returns the same type as its argument", for types you don't know in advance.
Should I use enum?
Usually not in new code. A union of string literals, or an as const object with a derived type, does the same job with plain JavaScript values, and works with Node's type stripping and the erasableSyntaxOnly option.
What's the difference between unknown and never?
unknown is the top type: every value fits in it, and you must narrow before using it. never is the bottom type: no value fits, which makes it useful for exhaustiveness checks and functions that never return.
Summary
- Union types (
A | B) allow several types; literal types and unions of literals describe fixed sets of values, replacing most enums. - Narrowing with
===,typeof,instanceof,in,Array.isArray, truthiness and type predicates gives each branch an exact type. - Discriminated unions share a literal tag; a
switchon the tag narrows each case, and aneverdefault makes the compiler check that every case is handled. - Generics with constraints write type-safe code for many types;
readonlytypes prevent accidental mutation. - Utility types (
Partial,Pick,Omit,Record, ...), indexed access,as constandsatisfiesderive and check types from a single source of truth.
Practice Questions
Why does this fail to compile, and how do you fix it without a type assertion?
function total(amount: number | string): number {
return amount + 10;
}
Answer
amount + 10 could be string concatenation when amount is a string, so the result type is string | number, not number. Narrow first:
function total(amount: number | string): number {
const n = typeof amount === "string" ? Number(amount) : amount;
return n + 10;
}
Add a "square" member with a side property to the Shape union in this article. What happens to area, and why is that useful?
Answer
area stops compiling, because in the default branch shape can now be the square, which isn't assignable to never. The compiler points you to every switch that needs a new case, instead of letting squares fall through at run time.
Write a generic function last that returns the last element of any array, typed so that last([1, 2]) is number | undefined.
Answer
function last<T>(items: readonly T[]): T | undefined {
return items[items.length - 1];
}
T is inferred from the argument: number for [1, 2], string for ["a"].
Previous: Type Checking with TypeScript: Annotations, Inference, Objects, Arrays and Functions

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.