interface VS type 키워드 차이점

김용진·2022년 11월 17일
0

typescript

목록 보기
2/3

declare

interface 키워드

  • 객체 앞에서만 쓸 수 있다. 원시값에 대한 자료형으로는 쓰일 수 없다.

  • computed value 사용이 불가능하다.

type Subjects = 'math' | 'science' | 'sociology';

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

type 키워드

  • 원시값(Primitive Type), 튜플(Tuple), 유니언(Union)타입을 선언할 때 사용하는 것이 좋다.

  • computed value 사용이 가능하다.

type Subjects = 'Math' | 'Science' | 'Sociology';

type Grades = {
  [key in Subjects]: string;
}

Index Signature의 사용 유무 - type alias 관련 내용

implement

extend

type과 interface 둘 다 확장이 가능하지만 interface는 선언적 확장이 가능하다.

interface Person {
  name: string;
  age: number;
}

interface Person { // 선언적 확장
  gender: string;
}

const jieun: Person = {
  name: 'jieun',
  age: 27,
  gender: 'female'
}

interface 키워드로 선언한 type은 같은 이름으로 선언을 다시 하면 자동으로 property의 확장이 되지만 type은 에러가 난다.

type Person = {
  name: string;
  age: number;
}

type Person = { // ❗️Error: Duplicate identifier 'Person'.
  gender: string;
}

interface 키워드가 확장 측면에서 성능이 상대적으로 좋다고도 한다.

팀 내에서 type과 interface의 적절한 쓰임새에 따라 공통으로 정해서 사용하는것이 좋을 것 같다.

요즘 type의 기능이 많이 좋아지고있어서 성능적인 부분은 점차 비교대상이 아니게 될 수도 있겠다.

Ref

Tecoble 기술 블로그
TS 공식 Docs

profile
기획/개발/디자인 다 하고싶은 프론트엔드 개발자

0개의 댓글