.
본문 바로가기
TypeScript

Type vs Interface

by 와칸다개발자 2021. 12. 5.

<지금 작성하는 포스트는 타입스크립트 4.2이상 버전을 기준으로 합니다.>

 

 

Type 과 Interface의 차이점은 무엇일까? 써드파티 라이브러리 코드를 보면 가끔

 

Type 별칭을 쓰는 부분이 있는데 필자는 Interface만 선호(?)해서 둘의 차이점이 무엇인지 알고 싶어졌다.

 

공식 핸드북에 홈페이지다.

 

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#differences-between-type-aliases-and-interfaces

 

Documentation - Everyday Types

The language primitives.

www.typescriptlang.org

 

일단 요약하자면 타입별칭과 인터페이스는 매우 유사하며,

 

중요한 차이점은 타입은 새로운 속성을 추가할 수 없다는 것

 

인터페이스는 항상 확장 가능하다는 것이다.

 

 

Interface 기본사용법

 

  interface IPerson  {
    name: string;
  }

  interface IDeveloper extends IPerson {
    skills: string[];
  }

  const developer1: IDeveloper = {
      name:'wakanda-developer',
      skills :[
          'typescript',
          'react'
      ]
  };

 

Type 기본사용법

 

  type TPerson = {
    name: string;
  }

  type TDeveloper = TPerson & {
    skills: string[];
  }

  const developer2: TDeveloper = {
      name:'wakanda-developer',
      skills :[
          'typescript',
          'react'
      ]
  };

 

진짜 차이점은 그래서 뭐???

 

새로운 속성을 추가하는 데에서 큰 차이점이 있다.

 

interface

 

  interface IPerson  {
    name: string;
  }

  interface IPerson {
    skills: string[];
  }

  const developer1: IPerson = {
      name:'wakanda-developer',
      skills :[
          'typescript',
          'react'
      ]
  };

 

동일한 인터페이스 명으로 선언병합이 가능하다. 

 

타입은 불가능하다.

 

Type

 

    type TPerson = {
      name: string;
    }

    type TPerson = {		// Error: duplicate identifier TPerson
      skills: string[];
    }

    const developer2: TPerson = {
        name:'wakanda-developer',
        skills :[
            'typescript',
            'react'
        ]
    };

 

Implements

 

type별칭에서 유니온타입은 Implements의 사용이 불가하다.

 

  interface User {
  	name:string;
    income: number;
  }

  class King implements User {
    name = 'king';
    income = 23435530000;
  }

  type User1 = {
   	name:string;
    income: number;
  };

  class King2 implements User1 {
    name = 'king';
    income = 23435530000;
  }

  type PartialUser = { name: string; } | { income: number; };

  // A class can only implement an object type or intersection of 
  // object types with statically known members
  
  class King3 implements PartialUser {
   	name = 'king';
    income = 23435530000;
  }
 
 

결론

type을 사용할 때 필자는 기존에 존재하던 타입을 개발자 입맛에 맞게 바꾸는거라 배웠고

 

나 또한 그렇게 사용하고 있다.

 

C계열 언어에서 #define의 용도처럼 

 

  #define INF1 1e15
  #define INF2 987654321
  #define LL long long
  #define VS vector<string>
  #define VI vector<int>
  #define VLL vector<LL>
  #define VB vector<bool>
  #define VC vector<char> 
  #define PII pair<int,int>
  #define PLL pair<LL,LL>

 

위 코드처럼 long long type을 LL로 치환해서 사용할 수 있다. 

 

공식 doc에서 type보다 interface의 사용을 권장하고 있고 기존에 존재하던 타입을 내 입맛에 바꿔 쓰고 싶다면

 

type을 사용하면 될 것 같다.

댓글