Union Type |
| Since: | TypeScript 1.0(2014) |
|---|
A type that accepts any one of multiple types — "either A or B." Multiple types are joined with | (pipe), and it is commonly used together with narrowing, where TypeScript automatically determines which type is in use.
Syntax
let variableName: Type1 | Type2 = value;
// Defined as a type alias
type TypeName = Type1 | Type2 | Type3;
// Discriminated union: uses a shared literal type property to identify each type.
type TypeName =
| { kind: "A"; property: Type }
| { kind: "B"; property: Type };
Syntax Reference
| Syntax | Description |
|---|---|
| Type1 | Type2 | Union type. Accepts either Type1 or Type2. |
| typeof variable === "typename" | A narrowing technique. Narrows down primitive types using typeof. |
| instanceof | A narrowing technique. Narrows the type based on whether a value is an instance of a class. |
| in operator | A narrowing technique. Narrows the type based on whether a specific property exists on an object. |
| Discriminated union | A design pattern that uses a shared literal type property (tag) to identify each member type. |
Sample Code
let value: string | number = "hello";
value = 42; // A number can also be assigned.
// Narrowing: use typeof to determine the type.
function printValue(val: string | number): void {
if (typeof val === "string") {
// Inside this block, val is treated as type string.
console.log(val.toUpperCase()); // String methods are available.
} else {
// Inside this block, val is treated as type number.
console.log(val.toFixed(2)); // Number methods are available.
}
}
printValue("hello"); // Outputs 'HELLO'.
printValue(3.14159); // Outputs '3.14'.
// Nullable type: use string | null to represent an unset value.
function greet(name: string | null): string {
if (name === null) {
return "Hello, Guest!";
}
return `Hello, ${name}!`;
}
console.log(greet(null)); // Outputs 'Hello, Guest!'.
console.log(greet("Kiryu")); // Outputs 'Hello, Kiryu!'.
// Discriminated union: use the kind property to identify the type.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;
function getArea(shape: Shape): number {
switch (shape.kind) {
case "circle":
// Here, shape is treated as type Circle.
return Math.PI * shape.radius ** 2;
case "square":
// Here, shape is treated as type Square.
return shape.side ** 2;
}
}
console.log(getArea({ kind: "circle", radius: 5 }).toFixed(2)); // Outputs '78.54'.
console.log(getArea({ kind: "square", side: 4 })); // Outputs 16.
Overview
A union type represents "one of multiple types" by combining them with |. In JavaScript, functions often accept both strings and numbers, and TypeScript union types let you express that intent explicitly in the type system.
When working with a union type variable, TypeScript only allows access to properties and methods that are common to all member types — until the type has been narrowed. By narrowing the type with if or switch, TypeScript knows the exact type within that block and grants access to its specific methods.
A discriminated union is a pattern where every member type shares a common literal type property (a tag), enabling safe narrowing in switch statements. Combined with exhaustiveness checking using never, TypeScript can detect at compile time if a newly added type is not handled.
If you find any errors or copyright issues, please contact us.