`type X = ...` — Name a Type, Reuse It Anywhere
Type Aliases
`type` lets you give a name to any type expression. Reuse, document intent, and keep code DRY.
What you'll learn
- Author a type alias
- Compose types from other types
- Decide between `type` and `interface` (coming next)
A type alias gives a name to a type. Once defined, you can use the name anywhere a type is expected.
The Syntax
type Email = string;
type Age = number;
type User = {
id: string;
email: Email;
age: Age;
}; type Name = TypeExpression. The right side can be any type —
primitive, object, union, function, anything.
Reuse the Same Shape
type Point = { x: number; y: number };
function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y);
}
const origin: Point = { x: 0, y: 0 }; Without the alias, you’d repeat { x: number; y: number } three
times.
Composition
Type aliases can reference other type aliases:
type Color = "red" | "green" | "blue"; // a union
type Theme = {
primary: Color;
background: Color;
}; You’ll mix aliases all the time.
Function Types
type Handler = (event: string) => void;
const onClick: Handler = e => console.log(e); A type alias for a function signature.
Generic Aliases (Preview)
type Maybe<T> = T | null;
const name: Maybe<string> = null;
const age: Maybe<number> = 36; Generics get a full chapter later. Just know that aliases can take type parameters.
type vs interface
Both can describe object shapes. The big difference:
typecan name ANY type (unions, primitives, tuples, functions)interfaceis just for object shapes — but supports declaration merging andextends
You’ll learn interface next. In practice:
- For simple object shapes: either works
- For unions, primitives, function types, mapped types: use
type - For something callers might
extend(library APIs): useinterface
For everyday app code, type is the safe default.
End of Chapter
That wraps the basics. Next chapter: the essentials — interfaces,
unions, narrowing, the “special” types like unknown and never.