Interfaces
9 min read
Interfaces
An interface declaration describes the shape of an object or the contract a class must fulfill. Like type aliases, interfaces are erased at compile time and produce no JavaScript output.
ts
interface Product {
id: number;
name: string;
price: number;
description?: string; // optional property
readonly sku: string; // cannot be reassigned after creation
}
const laptop: Product = {
id: 1,
name: "ThinkPad X1",
price: 1299,
sku: "TP-X1-2024"
};
laptop.sku = "other"; // Error — readonlyDeclaration merging
Interfaces support declaration merging: two interface declarations with the same name are automatically combined. This is how @types/ packages extend global types like Window or process.env.
ts
interface Window {
myAnalytics: { track: (event: string) => void };
}
// Now window.myAnalytics is typed everywhere in this projectExtending interfaces
ts
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
const rex: Dog = { name: "Rex", breed: "Labrador" };Ready to test yourself?
Practice TypeScript— quiz & coding exercises