Type Aliases & Union Types
type keyword, union (|), intersection (&), and discriminated unions
Skills taught: ts.type-alias, ts.union-type, ts.intersection-type, ts.discriminated-union
Type aliases and union types
// Type alias — name any type
type UserId = number;
type Username = string;
type IsActive = boolean;
const id: UserId = 42;
// Union type — value can be ONE of several types
type ID = string | number;
function findUser(id: ID): string {
if (typeof id === 'string') {
return `Looking up by username: ${id}`;
}
return `Looking up by numeric ID: ${id}`;
}
console.log(findUser('alice'));
console.log(findUser(42));
// Nullable types (union with null/undefined)
type MaybeString = string | null;
function greet(name: MaybeString): string {
if (name === null) return 'Hello, guest!';
return `Hello, ${name}!`;
}
console.log(greet('Alice'));
console.log(greet(null));
// Intersection type — value must satisfy BOTH
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged; // must have both name and age
const person: Person = { name: 'Bob', age: 30 };
console.log(person);
Discriminated unions
// Discriminated union — each variant has a 'kind' literal
type Circle = { kind: 'circle'; radius: number; };
type Rectangle = { kind: 'rectangle'; width: number; height: number; };
type Triangle = { kind: 'triangle'; base: number; height: number; };
type Shape = Circle | Rectangle | Triangle;
function area(shape: Shape): number {
switch (shape.kind) {
case 'circle': return Math.PI * shape.radius ** 2;
case 'rectangle': return shape.width * shape.height;
case 'triangle': return 0.5 * shape.base * shape.height;
// TypeScript knows all cases are handled — default would be 'never'
}
}
console.log(area({ kind: 'circle', radius: 5 }).toFixed(2));
console.log(area({ kind: 'rectangle', width: 4, height: 6 }));
console.log(area({ kind: 'triangle', base: 3, height: 8 }));
// Result type pattern — like Rust's Result<T, E>
type Result<T, E = Error> =
| { success: true; value: T }
| { success: false; error: E };
function parseNumber(s: string): Result<number, string> {
const n = Number(s);
if (isNaN(n)) return { success: false, error: `'${s}' is not a number` };
return { success: true, value: n };
}
const r1 = parseNumber('42');
const r2 = parseNumber('hello');
if (r1.success) console.log('Parsed:', r1.value);
if (!r2.success) console.log('Error:', r2.error);
Frequently Asked Questions
When should I use type instead of interface?
Use type for: unions (A | B), intersections (A & B), computed/mapped types, aliases to primitives (type UserId = number), and complex type expressions. Use interface for: object shapes that others will extend or implement, class contracts, and declaration merging (augmenting third-party types). In practice: start with interface for objects, switch to type when you need union/intersection/computed capabilities.