type과 interface의 차이는 무엇일까?

2024. 9. 5. 23:11WEB.DEV

반응형

타입스크립트로 작업을 하다 보면, 객체를 타이핑하기 위해 키워드로 'type'과 'interface'가 자주 사용되는걸 볼 수 있다.

중괄호를 사용한 객체 리터럴 방식으로 타입을 선언할 때 매번 일일이 작성하기에는 중복적인 요소가 많을 뿐만 아니라 변경이라도 발생하면 일일이 찾아서 수정을 해야 하고 그러다 보면 놓치는 부분이 발생할 수 밖에 없다. 그러면 예상치 못한 문제가 발생할 수도 있다.

그래서 type 또는 interface 키워드를 사용해 아래와 같이 선언을 해 반복적으로 사용해 중복을 없애고 변경 사항이 발생했을 때 일괄적으로 적용이 될수 있도록 할 수 있다.

type Item = {
  id: string;
  name: string;
  price: number;
  thumbnailUrl: string;
  ...
}

interface Item {
  id: string;
  name: string;
  price: number;
  thumbnailUrl: string;
  ...
}

const item1: Item = { ... };
const item2: Item = { ... };

그렇다면 type과 interface의 차이는 무엇일까?

확장(상속)하는 법

먼저 확장(상속)하는 방법이 다르다.

interface의 경우에는 extends 키워드를 이용해서 확장할 수 있다.

interface Item {
  id: string;
  name: string;
  price: number;
  thumbnailUrl: string;
  ...
}

interface BrandItem extends Item {
  brand: string;
  ...
}

const item: BrandItem = {
  id: 'asdklfjsdklfj',
  name: '반팔 티셔츠',
  price: 18000,
  thumbnailUrl: 'https://img....',
  brand: '테스트',
  ...
}

type의 경우에는 & 키워드를 이용해 확장할 수 있다.

type Item = {
  id: string;
  name: string;
  price: number;
  thumbnailUrl: string;
  ...
}

type BrandItem = Item & {
  brand: string;
  ...
}

const item: BrandItem = {
  id: 'asdklfjsdklfj',
  name: '반팔 티셔츠',
  price: 18000,
  thumbnailUrl: 'https://img....',
  brand: '테스트',
  ...
}

선언적 확장

다음으로 선언적 확장이 있다.

interface의 경우에는 선언적 확장이 가능하다. 이 말은 같은 이름으로 interface를 선언을 하게 되면 자동으로 확장이 된다고 볼수 있다.

interface Item {
  name: string;
  price: number;
}

interface Item {
  thumbnailUrl: string;
}

const item: Item = {
  name: '반팔 티셔츠',
  price: 18000,
  thumbnailUrl: 'http://img....'
}

반면 type의 경우에는 선언적 확장이 불가능하다.

type Item = {
  name: string;
  price: number;
}

type Item = {   // ❗️Error: Duplicate identifier 'Item'.
  thumbnailUrl: string;
}

자료형

다음으로 자료형이 있다.

interface의 경우에는 객체의 타입을 설정할 때는 사용할 수 있지만 원시 자료형에는 사용할 수 없다.

interface Item {
  name: string;
  price: number;
}

interface name extends string {}   // ❌ 불가능

type의 경우에는 객체 타입을 정의할 때도 사용할 수 있지만, interface와 달리 원시값이나 튜플, 유니언 타입을 선언을 할 때 사용할 수 있다.

type Name = string; type Address = string; type Position = [number, number];

type Store = { name: Name; address: Address; latlng: Position; }

computed vallue 사용

interface의 경우에는 computed value 사용이 불가능하다.

type Category = 'shirt' | 'coat' | 'pants';

interface Item {
  [key in Category]: string; // ❗️Error: A mapped type may not declare properties or methods.
}

반면 type은 computed value 사용이 가능하다.

type Category = 'shirt' | 'coat' | 'pants';

interface Item {
  [key in Category]: string;
}
 
728x90
반응형

'WEB.DEV' 카테고리의 다른 글

.css와 .module.css의 차이  (2) 2024.09.05
BFF(Backend For Frontend)가 무엇일까?  (0) 2024.09.05
자바스크립트 API 호출 방법  (2) 2022.06.30
자바스크립트 Async / Await  (0) 2022.06.30
자바스크립트 함수 선언 방법  (0) 2022.06.30