Interfaces
Declaring object shapes with required, optional, readonly, and extended interface fields.
Interfaces describe object shape. TypeScript uses structural typing, so any object with the required fields satisfies the interface.
Optional properties use ?. readonly properties can be set at creation but not reassigned later.
interface User {
id: string;
name: string;
email?: string;
readonly createdAt: Date;
}
const user: User = {
id: "u_1",
name: "Alice",
createdAt: new Date(),
};
user.name = "Bob";
// user.createdAt = new Date(); // errorInterfaces extend other interfaces to compose shapes without repeating shared fields.
interface Entity {
id: string;
createdAt: Date;
updatedAt: Date;
}
interface Product extends Entity {
name: string;
priceInCents: number;
}
const widget: Product = {
id: "p_1",
name: "Widget",
priceInCents: 999,
createdAt: new Date(),
updatedAt: new Date(),
};In production
Interfaces are open by design. That helps library authors augment framework types, but it can surprise you if you redeclare an interface you own. Prefer a type alias when you want to prevent declaration merging.
Enjoyed this? Get more software craft delivered to your inbox.