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.
'javascript & typescript' 카테고리의 다른 글
콜백함수, 프로미스, async/await 차이점과 예제 정리 (자바스크립트 비동기 처리) (0) | 2025.04.12 |
---|---|
JavaScript 배열 함수 모음 (0) | 2025.04.12 |
Single Field Updates vs. TypeScript Partial<T> (0) | 2025.02.15 |
Partial Type (0) | 2025.02.15 |
Index Type (0) | 2025.02.14 |