TypeScript Interfaces
Defining object shapes with interfaces
Basic Interface
interface User { # define interface
name: string;
age: number;
}
let user: User = {
name: 'John',
age: 25
};
Optional Properties
interface User {
name: string;
email?: string; # optional property
}
Readonly Properties
interface User {
readonly id: number; # cannot be changed
name: string;
}
Function Types
interface MathFunc {
(x: number, y: number): number; # function signature
}
const add: MathFunc = (x, y) => x + y;
Extending Interfaces
interface Person {
name: string;
}
interface Employee extends Person { # extend interface
employeeId: number;
}
Index Signatures
interface StringMap {
[key: string]: string; # dynamic properties
}
let map: StringMap = {
name: 'John',
city: 'NYC'
};