What is an interface in TypeScript?
Answer
An interface in TypeScript is a contract that defines the structure (shape) of an object — the properties and methods it must have. It is a purely TypeScript construct that disappears after compilation. Syntax: interface User { name: string; age: number; email?: string; } (the ? marks optional properties). A class can implement an interface with implements: class Admin implements User { name = "Alice"; age = 30; }. Interfaces can extend other interfaces: interface Admin extends User { role: string; }. They can describe function signatures: interface Greeter { (name: string): string; } and index signatures: interface StringMap { [key: string]: string; }. Declaration merging: multiple interface declarations with the same name are automatically merged — useful for extending third-party library types. Interfaces enforce the "duck typing" philosophy of TypeScript — if an object has the required shape, it satisfies the interface regardless of how it was created.
Previous
What is the unknown type and how does it differ from any?
Next
What is the difference between interface and type alias in TypeScript?