인터페이스란?
오브젝트의 타입을 설정하는 일종의 오브젝트 설계도
타입 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
}
그래서 어떤걸 쓸까?
- 단순히 타입스크립트에게 오브젝트의 모양을 알려주고 싶다: 인터페이스, 타입중 아무거나
- 타입 상속을 쉽게 하고싶다: 인터페이스
- 프로퍼티 축적이 반드시 필요하다: 인터페이스
'TypeScript' 카테고리의 다른 글
| [타입스크립트] 다형성(polymorphism) 제네릭(generic) 클래스(class) 인터페이스(interface) 합치기 (0) | 2022.11.20 |
|---|---|
| [타입스크립트] 인터페이스란? (인터페이스와 클래스의 차이점) (0) | 2022.11.17 |
| [타입스크립트] 타입의 종류와 인터페이스 (0) | 2022.11.15 |
| [타입스크립트] readonly(읽기전용) (0) | 2022.11.15 |
| [타입스크립트] 클래스 (0) | 2022.11.14 |
댓글