Interfaces
Define object structures with interfaces
#interfaces #types #objects
Interfaces
Interfaces define the shape of objects in TypeScript.
Basic Interface
interface User {
id: number;
name: string;
email: string;
age?: number; // Optional property
}
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
Interface Extension
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: number;
department: string;
}
const emp: Employee = {
name: "Bob",
age: 28,
employeeId: 1001,
department: "Engineering"
};
Function Interfaces
interface MathOperation {
(x: number, y: number): number;
}
const add: MathOperation = (x, y) => x + y;
const multiply: MathOperation = (x, y) => x * y;
Readonly Properties
interface Config {
readonly apiKey: string;
readonly endpoint: string;
}
const config: Config = {
apiKey: "secret",
endpoint: "https://api.example.com"
};
// config.apiKey = "new"; // Error: readonly property
Discover another handy tool from EditPDF.pro