What are interfaces in TypeScript? How do they differ from types?
Answer
Interfaces in TypeScript define the structure of an object. They can extend other interfaces and provide a way to enforce contracts in your code.
interface User {
name: string;
age: number;
isAdmin?: boolean; // Optional property
}
const user: User = { name: "Alice", age: 30 };
Difference:
- Interfaces are extendable through extends, while types use intersection (&) to combine types.
- Interfaces are primarily used for object shapes, whereas type is more versatile (can define union, tuple, or primitive types).
Read more about TypeScript interfaces