Sub topic 3
Naming types with type aliases
This chapter assumes you can write basic TypeScript annotations (string, number, boolean, arrays). It also assumes you know JavaScript objects, functions, and classes, and that you can run the compiler or use an editor that reports type errors. You should have seen interfaces in the previous chapter.
What a type alias is
A type alias gives a name to any type expression. The syntax is type Name = <type>. The alias does not create a new type. It is a label for a type that already exists, so the compiler treats the alias and the type it names as identical.
type UserId = number;
type Tags = string[];
type Point = { x: number; y: number };
const id: UserId = 42;
const plain: number = id; // fine: UserId is just another name for number
const tags: Tags = ["a", "b"];
const p: Point = { x: 1, y: 2 };Because the right-hand side can be any type expression, aliases cover more ground than interfaces. An interface can only describe an object-like shape. An alias can name a primitive, an array, a tuple, a function type, a union, an intersection, or an object shape.
| Right-hand side | Example | Can an interface name it? | Column |
|---|---|---|---|
| Primitive | `type Id = number` | No | |
| Object shape | `type P = { x: number }` | Yes | |
| Tuple | `type Pair = [string, number]` | Not as a tuple literal | |
| Function type | `type Fn = (s: string) => string` | Yes, with a call signature | |
| Union | `type Status = "a" \ | "b"` | No |
| Intersection | `type AB = A & B` | Not directly (use `extends`) |
Aliases for object shapes
For plain objects, an alias and an interface behave almost the same way. Structural typing, which you saw earlier, applies to both: a value matches if it has the required properties with compatible types.
type Point = {
x: number;
y: number;
};
function length(p: Point): number {
return Math.sqrt(p.x * p.x + p.y * p.y);
}
const origin3d = { x: 3, y: 4, z: 5 };
console.log(length(origin3d)); // 5, because origin3d has every property Point requiresThe call compiles because origin3d is a variable, not a fresh object literal. Passing { x: 3, y: 4, z: 5 } directly to length would trigger the excess property check and report an error. This check applies to aliases and interfaces alike.
An alias for an object shape supports the same member modifiers as an interface: optional properties with ? and read-only properties with readonly. The next chapter covers them in detail.
Unions and literal types
The strongest reason to reach for an alias is that only an alias can name a union. A union type says a value is one of several types. A literal type says a value is exactly one specific string, number, or boolean.
type Status = "idle" | "loading" | "done";
type Result =
| { ok: true; value: string }
| { ok: false; error: Error };
function describe(r: Result): string {
return r.ok ? r.value : r.error.message;
}Status accepts only three exact strings. Assigning "finished" to a Status variable is a compile-time error, which catches typos that a plain string would let through.
Result is a discriminated union. The property ok has a different literal type in each member, so checking r.ok narrows r to one member. Inside the true branch, TypeScript knows value exists. In the false branch, it knows error exists. Without the alias, you would have to repeat the whole union at every use.
Narrowing in practice
Narrowing works with if, switch, and the conditional operator. A switch over a discriminant is a common way to handle every case.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle":
return Math.PI * s.radius ** 2;
case "square":
return s.size ** 2;
}
}If you later add a third member to Shape and forget to handle it, the function no longer returns a value on every path. With strict enabled, the compiler reports the missing case. This is a good reason to model alternatives as unions rather than as one wide object with many optional properties.
Intersections
An intersection type, written with &, combines several types into one type that has all of their properties. Aliases are the natural way to name an intersection.
interface Named {
name: string;
}
interface Employee extends Named {
employeeId: number;
}
type Timestamps = { createdAt: Date; updatedAt: Date };
type EmployeeRecord = Employee & Timestamps;
const record: EmployeeRecord = {
name: "Grace",
employeeId: 7,
createdAt: new Date(),
updatedAt: new Date(),
};EmployeeRecord requires every property from Employee and from Timestamps. Later chapters compare intersections with extends in detail. For now, remember that & is how an alias builds a combined shape.
Function types and tuples
An alias names a function type with arrow syntax. This is often shorter than the interface call-signature form.
interface Formatter {
(input: string): string;
}
type FormatFn = (input: string) => string;
const upper: Formatter = (s) => s.toUpperCase();
const trim: FormatFn = (s) => s.trim();Both declarations describe the same kind of function. A tuple is a fixed-length array whose positions have known types. Aliases give tuples a readable name:
type Pair<A, B> = [A, B];
const entry: Pair<string, number> = ["age", 30];Aliases cannot be reopened
Once you declare an alias, you cannot add to it. Declaring the same name twice is an error. Interfaces behave differently: two declarations with the same name merge into one. The next chapters cover merging in detail.
interface Config {
host: string;
}
interface Config {
port: number;
}
const config: Config = { host: "localhost", port: 8080 };
// type Settings = { host: string };
// type Settings = { port: number }; // error: Duplicate identifier 'Settings'.This is a safety feature. An alias means exactly what its single declaration says, and no other file can change it by adding a second declaration.
Generic aliases
An alias can take type parameters, so one declaration describes many concrete types.
interface Box<T> {
value: T;
}
type Pair<A, B> = [A, B];
const numberBox: Box<number> = { value: 42 };
const entry: Pair<string, number> = ["age", 30];A generic alias can also name a union, which interfaces cannot do:
type Maybe<T> = T | null | undefined;
function firstOr<T>(items: T[], fallback: T): T {
return items.length > 0 ? items[0] : fallback;
}
const name: Maybe<string> = null;
console.log(firstOr([1, 2, 3], 0)); // 1Recursive aliases
An alias may refer to itself when the reference sits inside an object property, an array, or a tuple. This lets you describe tree-shaped data such as JSON.
type Json =
| string
| number
| boolean
| null
| Json[]
| { [key: string]: Json };
const doc: Json = { name: "Ada", tags: ["math", "code"], meta: { born: 1815 } };The compiler accepts the self-reference because it appears inside Json[] and an object type, where evaluation is deferred. A direct self-reference with no such wrapper, such as type Bad = Bad | string, is an error.
Common errors and gotchas
- Aliases do not create distinct types.
type UserId = numberandtype OrderId = numberare interchangeable. Passing anOrderIdwhere aUserIdis expected compiles. If you need to keep them apart, you need a technique such as branding, which is outside this chapter. - Repeating a name is an error. If two files declare
type Settingsin the same scope, the compiler reports a duplicate identifier. Interfaces would have silently merged. - Excess property checks still apply. Fresh object literals assigned to an alias type are checked for unknown properties.
- Error messages may show the expanded type. For aliases of complex types, hovering in an editor often displays the full expansion rather than the alias name. That is a display matter and not a different type.
Diagram: what an alias can name
Exercises
Exercise
You have type Status = "idle" | "loading" | "done";. Why does const s: Status = "finished"; fail, and why could you not write Status as an interface?
Show answer
"finished" is not one of the three literal types in the union, so it is not assignable to Status. An interface can only describe an object-like shape, so it cannot name a union of literal types. Only a type alias can.
Exercise
Given type UserId = number; and type OrderId = number;, does const o: OrderId = 5; const u: UserId = o; compile? Explain.
Show answer
Yes, it compiles. An alias is only a new name for an existing type, so UserId, OrderId, and number are all the same type. The compiler does not keep them apart.
Exercise
Write a type alias Shape for a circle with a radius or a rectangle with width and height, using a discriminant property so that a function can narrow it.
Show answer
type Shape = { kind: "circle"; radius: number } | { kind: "rectangle"; width: number; height: number }; Checking shape.kind then narrows to one member.