When working with TypeScript, developers often encounter two ways to define shapes for objects: interface and type. While they can look similar, there are important differences and best-use cases.
Key Differences
-
Extensibility:
-
interfacecan be extended multiple times by declaration merging or by using theextendskeyword. -
typeis closed after its definition. You can't merge or reopen atype, but you can create new types by intersecting them.
-
-
Declaration:
- Use
interfacefor defining the shape of objects, especially when you expect the structure to grow. - Use
typefor composing types, unions, primitives, and tuples.
- Use
-
Implements:
- Classes can
implementboth interfaces and types, but interfaces work more naturally with class implementation.
- Classes can
-
Union and Intersection:
- Only
typecan create union types (type AorB = A | B) and intersection types (type AB = A & B).
- Only
Examples
Interface Example
interface User {
name: string;
age: number;
}
interface User {
email: string;
}
// Merged into:
// { name: string; age: number; email: string }
Type Example
type User = {
name: string;
age: number;
};
// type User = { email: string } // Error: Cannot redeclare 'User'
type StringOrNumber = string | number;
When to Use Each
-
Use
interfacewhen:- You want to model the shape of objects and classes
- You expect extensions (from libraries or other code)
- Declaration merging is desirable
-
Use
typewhen:- You need to use unions or intersections
- You want to alias primitives or tuples (e.g.,
type Name = stringortype Point = [number, number]) - Complex type composition is required
Summary Table
| Feature | interface |
type |
|---|---|---|
| Extensible/mergeable | Yes | No |
| Supports unions | No | Yes |
| Suitable for objects | Yes | Yes |
| Use with primitives | No | Yes |
| Best for classes | Yes | Yes (but interface best) |
In practice: Use interface for data shapes and type for type transformations and combinations.
Top comments (0)