type vs interface
Both define the shape of an object, but have different capabilities.
Key differences
type | interface | |
|---|---|---|
| Object shape | Yes | Yes |
| Primitives/unions | Yes | No |
| Declaration merging | No | Yes |
| Extends | Via & | Via extends |
Mapped types ([K in keyof T]) | Yes | No |
Declaration merging (interface only)
ts
interface User { name: string; }
interface User { age: number; }
// result: { name: string; age: number; }Union types (type only)
ts
type ID = string | number;
type Status = 'active' | 'inactive' | 'banned';Extending
ts
// interface
interface Animal { name: string; }
interface Dog extends Animal { breed: string; }
// type
type Animal = { name: string; };
type Dog = Animal & { breed: string; };Rule of thumb: use
interfacefor object shapes that may be extended or merged (e.g. library public APIs). Usetypefor unions, intersections, and utility types.
updated
did you know it?