Sub topic 7
Describe Objects with Interfaces and Type Aliases
This chapter assumes you know JavaScript objects, functions, arrays, and basic TypeScript annotations. You have already configured TypeScript and renamed at least one JavaScript file to .ts.
An object shape describes which properties an object has and what values those properties contain. TypeScript checks that shape when you create an object or pass it to a function. This catches misspelled property names and missing data before the program runs.
Use an interface for a named object shape
An interface is a named description of an object. Use one when the shape represents a meaningful entity in your application.
interface User {
id: number;
name: string;
email?: string;
readonly createdAt: Date;
}
function describeUser(user: User): string {
const email = user.email ?? "no email";
return `${user.name} <${email}>`;
}
const user: User = {
id: 1,
name: "Ada Lovelace",
createdAt: new Date("2024-01-01"),
};
console.log(describeUser(user));The email? property is optional. A User may omit it, so code must account for the possibility that it is absent. The readonly modifier allows createdAt to be read but prevents assignment after the object is created.
TypeScript uses structural typing. An object matches User because it has the required properties with compatible types. It does not need to explicitly declare that it implements User.
flowchart TD
A[JavaScript object] --> B{Has required User properties?}
B -->|Yes| C[Can be used as User]
B -->|No| D[Compiler reports an error]
C --> E[Function receives checked shape]Use a type alias for flexible type combinations
A type alias gives a name to a type expression. It can describe an object just like an interface, but it can also represent unions, primitive values, tuples, and combinations of types.
type Product = {
sku: string;
price: number;
};
type LoadState =
| { status: "loading" }
| { status: "success"; products: Product[] }
| { status: "error"; message: string };
function render(state: LoadState): string {
if (state.status === "loading") {
return "Loading...";
}
if (state.status === "error") {
return `Error: ${state.message}`;
}
return `${state.products.length} product(s) loaded`;
}
console.log(render({ status: "success", products: [] }));The LoadState alias is a union. Each member has a status property with a different literal value. Checking state.status tells TypeScript which object shape remains in each branch.
Choose between interfaces and aliases
Both forms work well for ordinary object shapes. Prefer an interface when you expect other declarations to extend the shape or when you are modeling a public object-oriented contract. Prefer a type alias when the type combines several shapes or uses a union.
| Need | Suitable choice |
|---|---|
| A reusable entity shape | `interface` |
| A union of object shapes | `type` alias |
| Optional or readonly properties | Either |
| A tuple or primitive alias | `type` alias |
When two related interfaces share fields, extend one interface from another:
interface Identified {
id: number;
}
interface Admin extends Identified {
permissions: string[];
}
const admin: Admin = {
id: 7,
permissions: ["manage-users"],
};
console.log(admin.id, admin.permissions[0]);Exercise
What error should TypeScript report for const product: Product = { sku: "A-1" };, and what change fixes it?
Show answer
The required price property is missing. Add a numeric price, such as { sku: "A-1", price: 12.5 }.