TypeScript
Union & Literal Types
Union Types
A union type (A | B) means a value can be one of several types:
let pid: string | number;
// Both the following are acceptable
pid = 23;
pid = "23";
Narrowing
With a union, you can only use what all members have in common. Check which member you have first; TypeScript then narrows the type inside that branch:
function printId(id: string | number) {
id.toUpperCase(); // Error: Property 'toUpperCase' does not exist on type 'string | number'
if (typeof id === "string") {
console.log(id.toUpperCase()); // id: string
} else {
console.log(id.toFixed(2)); // id: number
}
}
Common ways to narrow:
| Check | Narrows to |
|---|---|
typeof x === "string" | primitives (string, number, …) |
x instanceof Date | class instances |
"email" in x | object types that have that key |
Array.isArray(x) | arrays |
x === null, if (x) | removes null / undefined |
Literal Types
A literal type is one exact value. On its own it isn't useful, but a union of literals describes a fixed set of allowed values:
type Direction = "north" | "east" | "south" | "west";
let heading: Direction = "north";
heading = "up"; // Error: Type '"up"' is not assignable to type 'Direction'
A union of string literals is often a lighter alternative to an enum: it needs no runtime code and works with plain strings.
const declarations get literal types automatically, let declarations get the wider type:
const a = "hello"; // type: "hello"
let b = "hello"; // type: string
Discriminated Unions
Give each member of a union a shared literal property (here kind). Checking it narrows to the right member:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}
null and undefined
With strictNullChecks (part of strict), null and undefined are separate types. A value that may be missing must say so in its type:
let nickname: string | undefined;
console.log(nickname.length); // Error: 'nickname' is possibly 'undefined'
console.log(nickname?.length); // OK: optional chaining
console.log(nickname ?? "none"); // OK: fallback value
