본문 바로가기
TypeScript

[타입스크립트] 인터페이스란? (인터페이스와 타입의 차이점)

by 메이플 🍁 2022. 11. 15.

인터페이스란?

오브젝트의 타입을 설정하는 일종의 오브젝트 설계도

 

타입 vs 인터페이스

  • 공통점: 오브젝트의 모양을 결정할 수 있다 (오브젝트 타입지정 가능)
  • 타입: 여러 데이터의 타입을 지정할 수 있다
  • 인터페이스: 오직 오브젝트 데이터의 타입만을 지정할 수 있다

타입 예제

type Team = 'red' | 'blue' | 'yellow'
type Health = 1 | 5 | 10

type Player = {
  nickname: string,
  team: Team,
  health: Health
}

const nico: Player = {
  nickname: 'nico',
  team: 'yellow',
  health: 10
}

인터페이스 예제

type Team = 'red' | 'blue' | 'yellow'
type Health = 1 | 5 | 10

interface Player {
  nickname: string,
  team: Team,
  health: Health
}

const nico: Player = {
  nickname: 'nico',
  team: 'blue',
  health: 1
}

 

인터페이스 프로퍼티를 읽기 전용(readonly)으로 만들기

interface User {
  readonly name: string
}

interface Player extends User {
  
}

const nico: Player = {
  name: 'nico'
}

nico.name = 'lalala' // 에러발생: readonly 수정불가

 

인터페이스만이 가지고 있는 특징

1. 타입 상속 (extends)

인터페이스 User와 Players는 같은 타입을 가진다.

interface User {
  name: string
}

interface Player {
  name: string
}

인터페이스 Player가 User의 타입을 상속받아 반복작업을 줄일 수 있다.

interface User {
  name: string
}

// extends로 상속
interface Player extends User {
  
}

type일때 상속받는법 (&기호)

type User = {
  name: string
}

// &: and 연산자로 상속
type Player = User & {
  
}

const nico: Player = {
  name: 'nico'
}

2. 프로퍼티 축적

인터페이스를 각각 3번 만들기만 하면 타입스크립트가 알아서 합쳐준다. type일때는 프로퍼티를 축적할 수 없다.

interface User {
  name: string
}

interface User {
  lastName: string
}

interface User {
  health: number
}

const nico: User = {
  name: 'nico',
  lastName: 'nico',
  health: 10
}

 

 

그래서 어떤걸 쓸까?

  • 단순히 타입스크립트에게 오브젝트의 모양을 알려주고 싶다: 인터페이스, 타입중 아무거나
  • 타입 상속을 쉽게 하고싶다: 인터페이스
  • 프로퍼티 축적이 반드시 필요하다: 인터페이스

댓글