type vs interface 타입스크립트

모성종·2022년 7월 11일
1

타입스크립트에서 타입을 선언할 때 type 키워드와 interface 키워드를 사용할 수 있다.
이 두가지 키워드의 공통점으로는 둘다 객체의 모양을 특정하여 타입스크립트에게 알려주기 위해 사용한다는 것이다.

일반적으로
type은 자료형을 만들 때 사용하고
interface는 객체의 명세(형태)를 작성할 때 사용하는 것으로 보는 게 바람직하다.

그래서 타입스크립트 커뮤니티에서는 클래스와 객체의 모양을 정의하고 싶은 경우 interface를 사용하고 그 외 나머지 상황에서는 type를 사용할 것을 추천하고 있다.
Types or Interfaces

  • consider using type for your React Component Props and State, for consistency and because it is more constrained.
  • public API를 정의할 때 interface를 사용해라. 사용자가 interface를 확장하거나 속성을 병합할 수 있다.
  • 일관성과 더 제약적인 이유로 리액트 컴포넌트의 props, state를 작성할 때는 type을 고려해라

type

객체의 타입을 string, number와 같은 concrete 타입이 아닌 특정 값으로 한정지을 때 아래와 같이 사용할 수도 있다.

type Color = 'red' | 'blue' | 'green'

type 키워드의 일반적인 사용

type Player = {
  nickname: string,
  healthBar: number
}
const mo: Player {
  nickname: 'mocci',
  healthBar: 100
}

Player타입은 string 형태의 nickname이라는 key, number 형태의 healthBar key 두개를 갖는 타입이다.

interface

객체의 모양을 타입스크립트에게 설명해주기 위해서만 사용된다.

interface 키워드의 일반적인 사용

interface Player {
  nickname: string,
  healthBar: number
}
const mo: Player = {
  nickname: 'mocci',
  healthBar: 100
}

type과 interface 사용 비교

두 가지 방법은 타입에 대해 확장할 때 다르게 표현한다.

type 확장

type User = {
  name: string
}
type Player = User & {
  age: number
}

interface 확장

interface User {
  name: string
}
interface Player extends User {
  age: number
}

위 두 방법 모두 결과적으로 Player 타입은 name, age 키를 갖는 결과는 동일하다.

interface 합치기 (property 쌓기)

interface 키워드가 가지는 장점으로는 동일한 이름의 interface를 작성하여 property를 누적해서 사용할 수 있다.

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

const mo: Person = {
  name: 'mocci',
  age: 30,
  height: 170
}

Person은 name, age, height 키를 갖게 된다. type 키워드를 사용하면 이런 방법을 쓸 수 없다.

profile
FE Developer

0개의 댓글