TypeScript

TS에서 type과 interface의 차이점은?

단점이없어지고싶은개발자 2022. 6. 16. 16:26
반응형

타입스크립트에서 type도 타입이 지정이 가능하고, interface도 타입이 지정이 가능한데 그렇다면 두 개의 차이점이나 공통점은 무엇일까? 라는 궁금중이 생겼다.

 

기본 사용법

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

const first: PeopleInterface = {
  name: 'abc',
  age: 123,
};

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

const second: PeopleType = {
  name: ' abc',
  age: 123,
};

위에 코드처럼 interface도 type처럼 객체의 타입을 지정해줄 수 있는 또 다른 방법이다.

 

서로 다른 확장법 

interface는 extends를 이용, type은 & 를 이용.

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

interface UserInterface extends PeopleInterface {
  id: string;
}

const first: UserInterface = {
  name: 'abc',
  age: 123,
  id: '123',
};

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

type UserType = PeopleType & {
  id: string;
};

const second: UserType = {
  name: ' abc',
  age: 123,
  id: '123',
};

 

선언적 확장에 대한 차이

같은 interface 명으로 만든다면 자동으로 확장이 가능하다.

interface User {
  id: string;
}

interface User {
  password: string;
}

const src: User = {
  id: 'abc',
  password: "123",
};

Type은 식별자가 중복되어서 에러가 발생한다

interface는 객체만 가능하다 

computed value의 사용

type은 가능하지만, interface는 불가능하다

type nickname = 'firstName' | 'lastName'

type NameTypes = {
  [key in nickname]: string
}

const yc: NameTypes = { firstName: 'hi', lastName: 'yc' }

interface NameInterface {
  [key in names]: string
  //interface에는 불가하다
}

 

& 사용했을때의 오류

interface는 속성간 충돌을 해결하기 위해 단순히 객체 타입을 만든다. interface는 객체의 타입을 만들기 위한 것이고, 객체만을 위해 사용되기 때문에 단순히 합치기만 하면 되지만, 타입의 경우는 다르다. 재귀적으로 순회하면서 속성을 merge하게 되는데, 이 경우에 일부는 'never'라는 키워드를 만날 수 있다. type은 원시 타입이 올 수도 있기 때문이다

type type2 = { a: 1 } & { b: 2 } // 잘 머지됨
type type3 = { a: 1; b: 2 } & { b: 3 } // resolved to `never`

const t2: type2 = { a: 1, b: 2 } // good
const t3: type3 = { a: 1, b: 3 } // Type 'number' is not assignable to type 'never'.(2322)
반응형

'TypeScript' 카테고리의 다른 글

제네릭(Generics)  (0) 2022.07.17
Record Type  (0) 2022.07.16
react에서 type 설정 하는 방법  (0) 2022.05.13
interface 사용법  (0) 2022.05.13
타입스크립트로 HTML 변경과 조작할 때 주의점들  (0) 2022.05.12