Syntax
type Union = TypeA | TypeB;
type Intersection = TypeA & TypeB;Examples
Union Types
A value that can be one of several specific types.
type ID = string | number;
function printId(id: ID) {
console.log(`ID: ${id}`);
}
printId(101); // OK
printId("abc-123"); // OK
// printId(true); // Error - boolean is not part of the unionIntersection Types
Combining multiple types into one that has all of their members.
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged; // must have BOTH name and age
const person: Person = {
name: "Alice",
age: 25
};
// A value missing either "name" or "age" would fail to type-checkBest practices
- Use union types to model a value with a small, known set of valid shapes or states, like a status field
- Use intersection types to compose smaller, reusable type fragments into a larger, complete type
- Combine unions with discriminant properties (a shared "kind" or "type" field) to enable clean type narrowing in conditional logic
- Be cautious intersecting types with conflicting property types - the result can resolve to never for that property, which is easy to miss
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook