TypeScript Essentials
TypeScript Interfaces
TypeScript Interfaces
Section titled “TypeScript Interfaces”Interfaces define the structure of objects and provide type checking.
Basic Interface
Section titled “Basic Interface”interface User { name: string; age: number; email: string;}
const user: User = { name: "Alice", age: 25, email: "alice@example.com"};Optional Properties
Section titled “Optional Properties”interface User { name: string; age: number; email?: string; // Optional}
const user: User = { name: "Bob", age: 30 // email is optional};Readonly Properties
Section titled “Readonly Properties”interface Config { readonly apiKey: string; readonly baseUrl: string;}
const config: Config = { apiKey: "abc123", baseUrl: "https://api.example.com"};
// config.apiKey = "new"; // Error!Method Signatures
Section titled “Method Signatures”interface Calculator { add(a: number, b: number): number; subtract(a: number, b: number): number;}
const calc: Calculator = { add: (a, b) => a + b, subtract: (a, b) => a - b};Extending Interfaces
Section titled “Extending Interfaces”interface Person { name: string; age: number;}
interface Employee extends Person { employeeId: string; department: string;}
const employee: Employee = { name: "Alice", age: 25, employeeId: "E123", department: "Engineering"};Index Signatures
Section titled “Index Signatures”interface StringMap { [key: string]: string;}
const headers: StringMap = { "Content-Type": "application/json", "Authorization": "Bearer token"};Interface vs Type
Section titled “Interface vs Type”// Interfaces can be extended/mergedinterface Animal { name: string;}interface Animal { age: number;}// Animal now has both name and age
// Types use intersectiontype Pet = { name: string } & { age: number };