타입과 인터페이스의 차이에 대해 알고 있는가? 업무 진행 시 어떠한 상황에서 타입을 사용하고 어떠한 상황에서 인터페이스를 사용하는가? 타입과 인터페이스의 특징은 객체의 타입 이름을 지정하는 것이다. 둘의 기능에는 공통점과 차이점이 있다.
상속을 받는 방법의 차이
interface는 extends를 사용하며, type은 &를 이용해 상속을 통한 확장을 한다.
interface interface1 {
a: string;
}
interface interface2 extends interface1 {
b: string;
}
const interfaceConst: interface2 = {
a: "a",
b: "b"
}
type type1 = {
a: string;
}
type type2 = type1 & {
b: string;
}
const typeConst: type2 = {
a: 'a',
b: 'b',
}
자동 확장 기능의 차이
interface는 동일한 이름의 객체를 여러 번 선언할 시 자동으로 확장된다. 하지만 type은 불가능하다.
튜플, 단순한 원시값의 타입 선언의 경우 type을 사용한다.
type num = 1 | 2 | 3;
type arr = Array<string>;
type str = string;
type union = { a: string } | { b: string };
type interaction = { a: string, b: string } & { a: string, c: string }
const interactionTest : intersection = {
a: 'a',
b: 'b',
c: 'c'
}
const unionTest: union = {
a: 'a'
}
결론적으로 type의 특성이 필요할 때 type을 사용해야 한다. 예컨데 튜플이나 원시값의 타입 선언이 필요한 경우처럼 말이다.
'Frontend > TypeScript' 카테고리의 다른 글
TypeScript What does "keyof typeof" mean? (0) | 2023.01.18 |
---|---|
TypeScript super vs this & setter/getter (0) | 2023.01.16 |
TypeScript - infer (0) | 2023.01.14 |
TypeScript 전개 연산자(Spread 문법) (0) | 2023.01.13 |
TypeScript enum과 union type, 언제 사용해야 할까? (0) | 2023.01.12 |