Interface
A TypeScript construct that defines the structure of an object, specifying the names and types of its properties and methods.
Overview
Interfaces in TypeScript are a powerful way to define contracts within your code. They describe the shape that objects should have, making your code more predictable and easier to understand. Interfaces support optional properties, readonly properties, and can be extended or implemented by classes.
Example
typescript// Basic interface interface User { id: number; name: string; email: string; } const user: User = { id: 1, name: 'Alice', email: '[email protected]' }; // Optional and readonly properties interface Product { readonly id: number; // Cannot be modified name: string; price: number; description?: string; // Optional } // Function types in interfaces interface SearchFunc { (source: string, substring: string): boolean; } const search: SearchFunc = (src, sub) => { return src.includes(sub); }; // Extending interfaces interface Person { name: string; age: number; } interface Employee extends Person { employeeId: number; department: string; } // Implementing interfaces in classes interface Animal { name: string; makeSound(): void; } class Dog implements Animal { name: string; constructor(name: string) { this.name = name; } makeSound() { console.log('Woof!'); } } // Index signatures interface StringArray { [index: number]: string; } const myArray: StringArray = ['Bob', 'Alice'];
Key Points
- Defines object structure
- Supports optional and readonly properties
- Can extend other interfaces
- Can be implemented by classes
- Flexible and composable
Learn More
- Type - TypeScript types
- TypeScript - TypeScript language
- Class - ES6 classes
- TypeScript Docs: Interfaces