Interfaces
| Describe a shape | |
| Optional members | |
| Readonly members | |
| Extend interfaces |
Describe a shape
An interface lists the members an object must carry. The compiler checks every assigned object against that list and rejects extras of the wrong type and missing members alike:
interface User {
id: number;
name: string;
}
const ada: User = { id: 1, name: "Ada" };
console.log(ada.name);
Ada
The ada object matches the User shape member for member. Forgetting the name field or storing text in id would stop the compile with the exact spot named.
Optional members
A question mark marks a member that may be absent. Optional members fit data that appears only in some cases, such as a profile biography:
interface Profile {
login: string;
bio?: string;
}
const me: Profile = { login: "ada" };
console.log(me.login);
ada
The object stays valid without a bio, and adding one later is equally fine. Keep required members plain and mark only the truly skippable ones as optional.
Readonly members
The readonly marker locks a single member after creation. Identifiers such as database keys must never change, and the compiler now enforces that rule:
interface Doc {
readonly id: number;
title: string;
}
const doc: Doc = { id: 7, title: "Guide" };
console.log(doc.title);
Guide
Reading doc.id works anywhere, while assigning to it fails the compile. Use readonly for identity fields and leave editable content such as title open to change.
Extend interfaces
One interface can extend another to inherit its members and add new ones. Specialized shapes reuse the shared base instead of copying its fields:
interface User {
id: number;
}
interface Admin extends User {
level: number;
}
const boss: Admin = { id: 1, level: 5 };
console.log(boss.level);
5
Admin carries both id from User and its own level. Every Admin still counts as a User, so functions written for User accept admins with no extra work.
Next: Unions and literals
Article author: Arthur Isaev