Front-End/Typescript
[Typescript] Type과 interface의 차이
kimik
2021. 7. 22. 01:25
interface ExampleInterface1 extends ExampleInterface2 {
age: number;
}
type ExampleType1 = ExampleType2 & {
age: number;
};
interface의 경우 extends로, type은 &으로 확장
interface ExampleInterface {
id: number;
name: string;
}
interface ExampleInterface {
age: number;
}
Interface는 동일한 이름으로 다시 선언하여 확장이 가능
type GenericType = { [x: string]: number };
type NormalType = { x: number };
const obj1: NormalType = {
x: 1,
};
const obj2: GenericType = obj1;
Type은 위와같이 obj2(GenericType)에 obj1(NormalType)을 할당해도 에러가 나지않지만,
interface GenericInterface {
[x: string]: number;
}
interface NormalInterface {
x: number;
}
const obj1: NormalInterface = { x: 1 };
const obj2: GenericInterface = obj1; // error
Interface의 경우 ob2(GenericInterface)에 obj1(NormalInterface)을 할당하면 에러
interface GenericInterface {
[x: string]: number;
}
type NormalType = { x: number };
const obj1: NormalType = { x: 1 };
const obj2: GenericInterface = obj1;
obj2(GenericInterface)에 obj1(NormalType)을 할당하면 에러가 나지 않지만,
type GenericType = { [x: string]: number };
interface NormalInterface {
x: number;
}
const obj1: NormalInterface = { x: 1 };
const obj2: GenericType = obj1; // error
obj2(GenericType)에 obj1(NormalInterface)를 할당하면 에러
결론은 일반적인상황에서 큰 차이는 확장방법과 같은 이름으로 선언이 가능한가 정도이고, 세세하게는 type, Interface끼리
할당할때의 에러가 차이가 있다.