TS Type Aliases
A type alias gives a name to any type — union, intersection, primitive, tuple, object, function. More flexible than an interface; nearly the same in practice.
Basic alias
TS
type UserId = number | string;
type User = {
id: UserId;
name: string;
email?: string;
};
const u: User = { id: 1, name: 'Ada' };
Aliases compose with intersection
TS
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged & { greet(): string };
Aliases for function shapes
TS
type Handler = (event: Event) => void; type Reducer<S, A> = (state: S, action: A) => S;
Generic aliases
TS
type Result<T, E = string> =
| { ok: true; value: T }
| { ok: false; error: E };
const r: Result<number> = { ok: true, value: 42 };
Recursive aliases
TS
type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue };
Aliases for primitive narrowing
TS
type Email = string; // semantic only — no runtime check type Direction = 'up' | 'down' | 'left' | 'right';
For real branded types (so a plain string can't sneak in where an Email is expected) use a "branded" pattern:
TS
type Email = string & { readonly __brand: 'Email' };
const e = 'ada@example.com' as Email;
Tip: When in doubt, start with
type. Reach for interface only when you need declaration merging (for example, augmenting global types like Window or Express.Request).Example
Example
type UserId = number | string;
type User = {
id: UserId;
name: string;
email?: string;
};
const u: User = { id: 1, name: 'Ada' };
console.log(u);
Try it Yourself »
Exercise
Declare a type alias.
UserId = number | string;
Four letters.
Discussion
Loading…