Interfaces
Define object shapes with interface — required, optional, readonly
Skills taught: ts.interface, ts.optional-properties, ts.readonly-properties, ts.interface-extends
Defining and using interfaces
// Define an interface — object shape contract
interface User {
id: number;
name: string;
email: string;
age?: number; // optional property
readonly createdAt: string; // cannot be changed after creation
}
// Create an object satisfying the interface
const alice: User = {
id: 1,
name: 'Alice',
email: 'alice@example.com',
createdAt: '2024-01-15'
};
// TypeScript catches missing required properties:
// const bad: User = { id: 2, name: 'Bob' };
// Error: Property 'email' is missing
// Function that uses the interface
function greetUser(user: User): string {
return `Hello, ${user.name}! (${user.email})`;
}
console.log(greetUser(alice));
// Interface with method
interface Greeter {
greeting: string;
greet(name: string): string;
}
const formal: Greeter = {
greeting: 'Good day',
greet(name) { return `${this.greeting}, ${name}.`; }
};
console.log(formal.greet('Alice'));
Extending interfaces
interface Animal {
name: string;
sound: string;
}
// Extends: Dog has everything Animal has, plus extras
interface Dog extends Animal {
breed: string;
age: number;
fetch(): void;
}
const rex: Dog = {
name: 'Rex',
sound: 'Woof',
breed: 'Labrador',
age: 3,
fetch() { console.log(`${this.name} fetches the ball!`); }
};
rex.fetch();
// Multiple interface extension
interface Serializable { serialize(): string; }
interface Versioned { version: number; }
interface Config extends Serializable, Versioned {
name: string;
}
const cfg: Config = {
name: 'prod',
version: 2,
serialize() { return JSON.stringify({ name: this.name, v: this.version }); }
};
console.log(cfg.serialize());
// Index signature — flexible object keys
interface ScoreMap {
[username: string]: number;
}
const scores: ScoreMap = {};
scores['Alice'] = 95;
scores['Bob'] = 87;
console.log(scores);
Frequently Asked Questions
What's the difference between interface and type alias?
For object shapes, they're mostly equivalent. Key differences: interfaces can be extended with extends and support declaration merging (two declarations with same name merge); type aliases support union types (A | B), intersection types (A & B), and mapped types. Rule of thumb: use interface for objects and class contracts, type for unions and complex type expressions.