TS, type vs interface

껌뻑이·2021년 8월 11일
0

TypeScript

목록 보기
2/4
post-thumbnail

type vs interface

TS에서 type alias의 방법과 interface의 방법을 비교해보자

공통점

공통점은 type과 interface을 사용해 타입을 정의하고 지정한다는 점이다.

코드

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

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

둘 다 똑같이 객체에 대입하면 타입이 지정이 된다.

차이점

차이점은 공통점에서의 코드를 봤듯이 선언하는 면에서 type을 쓰고, interface를 쓰고 '='로 선언하냐 안하냐의 차이도 있지만 타입을 확장하는 방법에 가장 큰 차이가 있다.

코드

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

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

type Person = Animal & {
  address: string;
}

interface Person extends Animal {
  address: string;
}

type과 interface 둘 다 Person에 Animal의 타입을 확장하고 있지만 확장하는 방법이 다르다.

결론

type과 interface는 확장하는 면에서 가장 큰 차이점을 보인다.

type
= 연산자 후 확장할 타입 alias명과 & 연산자를 붙여서 확장

interface
새로 지정할 interface명과 extends 기호와 확장할 interface명을 붙여서 확장

0개의 댓글