javascript & typescript
type aliases vs interfaces
neal89
2025. 2. 14. 14:47
In TypeScript, both type aliases and interfaces are used to define custom types, but they have distinct differences. Here's a comparison:
Aspect type alias interface
Purpose | Defines a new name for any type, including primitives, unions, tuples, and object types. | Primarily used to define the structure of an object, specifying its properties and methods. |
Declaration Merging | Does not support declaration merging; redefining the same type alias results in an error. | Supports declaration merging, allowing multiple declarations with the same name to be merged into a single interface. |
Extensibility | Can extend other types using intersection (&) to combine multiple types. | Can extend other interfaces or types using the extends keyword, and can be extended by classes using the implements keyword. |
Usage | Suitable for defining complex types, such as unions or tuples, and for creating aliases for existing types. | Ideal for defining the shape of objects and ensuring that classes adhere to a specific structure. |
Example of Declaration Merging with Interfaces:
interface Person {
name: string;
}
interface Person {
age: number;
}
// The merged interface is equivalent to:
interface Person {
name: string;
age: number;
}
In this example, the two Person interface declarations are merged into one, combining their properties.
Example of Extending Types and Interfaces:
// Using type alias with intersection
type Animal = { name: string };
type Bear = Animal & { honey: boolean };
// Using interface with extends
interface Animal {
name: string;
}
interface Bear extends Animal {
honey: boolean;
}
In these examples, both type and interface are used to create new types that build upon existing ones, but the syntax differs.