Loading lessons...
Type Aliases & Union Types
Type Aliases & Union Types
Type aliases allow naming any type definition, including primitives, unions, tuples, and functions.
Defining Type Aliases
Syntax: type AliasName = Type Definition;
type UserID = string | number;
type Point = { x: number; y: number };
let id: UserID = 101;
id = "usr_999"; // Valid due to Union type!
Union Types (|)
Unions allow a value to be one of several specified types.
function printID(id: string | number) {
if (typeof id === "string") {
console.log(id.toUpperCase()); // Narrowed to string
} else {
console.log(id.toFixed(2)); // Narrowed to number
}
}
Type Aliases vs Interfaces
| Feature | Interface | Type Alias |
|---|---|---|
| Object Types | Supported | Supported |
| Unions & Primitives | No | Supported |
| Declaration Merging | Yes | No |
| Extends / Combines | extends | & (Intersection) |
TL;DR
- Use
typealiases to give custom names to primitive, union, tuple, or function types. - Union types (
A | B) accept values matching type A OR type B.