No More Confusion About TypeScript’s Type and Interface
Type aliases are extended by &, while interfaces are extended by extends.
So can an interface extend the type defined by the type alias through extends? The answer is yes. Additionally, type aliases can also extend defined interface types via the & operator.
Differences
- Type aliases can define aliases for primitive types, union types, or tuple types, while interfaces cannot:
type MyNumber = number; // primitive type
type StringOrNumber = string | number; // union type
type Point = [number, number]; // tuple type
- Interfaces with the same name are automatically merged(Declaration Merging), while type aliases are not:
When to use type
- When defining aliases for primitive types, use
type - When defining a tuple type, use
type - When defining a function type, use
type - When defining union types, use
type - When defining the mapped types, use
type
When to use interface
- When you need to take advantage of the declaration merging feature, use
interface - When defining an object type and no need to use type, use
interface