본문 바로가기
  • 저희는 평생 개발할 운명이걸랑요
Tech.log/프론트엔드

[Interfaces vs Type Aliases]

by SpaciousKitchen 2021. 4. 10.

Type Aliases 비교적 Interfaces 처럼 작용한다. 이 둘은 무슨 차이가 있을까 ?

 

Interfaces는 여러곳에서 새로운 이름(new name)을 만든다. 반면 Type Aliases 유일(unique)하다.

 

두 코드를 비교해 보자

 

//interface 예시

interface Window {
  title: string
}

interface Window {
  ts: import("typescript")
}

const src = 'const a = "Hello World"';
window.ts.transpileModule(src, {});

해당 코드를 사용하면, 기존에 존재하는 Window interface에  'ts' 라는 새로운 field를 추가하게 된다.

 

그러나 

 

//type예시

type Window = {
  title: string
}

type Window = {
  ts: import("typescript")
}

// Error: Duplicate identifier 'Window'.

type Window에 경우는 에러는 내뿜는다.

 

 

따라서, Interfaces는 확장 가능 type Aliases는 extend되거나 implement될 수 없다. 

 

 

그럼 언제 Type Aliases 를 써야하는가 ?

 

 interface로 표현할 수 없는 형태(shape)이고 union, tuple 일때 사용한다.

 

//예시 Union-Type

type Race = 'string | number'; // string과 number를 동시에 타입으로 지정해줍니다.
const win: Rating = 1;

function racePrint(rating: Race) {
  console.log(rating);
};

racePrint(1); // 1
racePrint(승리); // '승리'

 

 

'Tech.log > 프론트엔드' 카테고리의 다른 글

[브라우저의 렌더링 원리]  (0) 2021.04.22
[React] Component와 Props 알아보기  (0) 2021.04.16
Pre-rendring[SSR vs CSR _2]  (0) 2021.04.12
SSR vs CSR ? 그리고 ..  (0) 2021.04.12
[타입스크립트, 왜 쓰니 ?]  (0) 2021.04.05

댓글