Difference between type & interface Typescript
The differences between type and interface in TypeScript can be summarized as follows:
1. Syntax and Usage
-
Type:
- Can define primitive types, union types, intersection types, and more complex structures.
- Uses the
typekeyword. - Example:
type Point = { x: number; y: number };
-
Interface:
- Primarily used to define the shape of objects and can include methods.
- Uses the
interfacekeyword. - Example:
interface Point { x: number; y: number; }
2. Extensibility
-
Type:
- Cannot be reopened to add new properties once defined. You create new types instead.
-
Interface:
- Can be extended by other interfaces, allowing for a more flexible structure.
- Example:
interface Shape { area(): number; } interface Circle extends Shape { radius: number; }
3. Merging
-
Type:
- Does not support declaration merging. If you declare a type with the same name again, it will result in an error.
-
Interface:
- Supports declaration merging, allowing multiple declarations with the same name to combine their members.
- Example:
interface User { name: string; } interface User { age: number; } // Merged User interface now has both name and age properties.
4. Use Cases
-
Type:
- More versatile for defining complex types like unions and intersections.
-
Interface:
- Preferred for defining object shapes, especially when working with classes and when needing extensibility.
In general, you can often use either type or interface interchangeably for defining object shapes, but interfaces are typically favored for this purpose due to their extensibility and merging capabilities.