- An interface is a syntactical contract that defines the structure of an object.
- It specifies what properties & methods an object should have without providing the implementation details.
- Interfaces can be used to enforce type-checking & ensure that objects adhere to a specific shape, promoting code consistency and maintainability.
Key points:
- Shape Definition: Defines properties & methods.
- Type Checking: Ensures objects conform to specified structure.
- Extensibility: Supports inheritance, allowing one interface to extend another.
- Implementation: Classes can implement interfaces to ensure they follow the defined contract.
Example
interface Person {
name: string;
age: number;
greet(): void;
}
class Employee implements Person {
constructor(public name: string, public age: number) {}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}