[TIL] type & interface

·2023년 12월 19일
1

TIL

목록 보기
59/85
post-thumbnail

Type

type Team = "red"|"blue"|"yellow" // 특정 값을 갖도록 설정할 수 있다.
type Health = 1 | 5 | 10

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

const hyewon :Player = {
    nickname: "hyeng",
    team: "red",
    healthBar: 10
}

[Type 의 용도]

  • 특정 값이나 객체에 대한 타입을 지정할 수 있다.
    (interface는 객체에 대한 모양만 지정 가능)
  • Type alias 를 만들 수 있다.
  • 타입을 특정한 값을 갖도록 제한할 수 있다.

interface

인터페이스 선언은 객체 유형을 지정하는 또 다른 방법이다.

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

type과 interface의 차이점

타입과 인터페이스는 매우 유사해서 대부분의 경우 자유롭게 선택할 수 있다. interface의 거의 모든 기능을 type에서 사용할 수 있다.
그러나 몇가지 중요한 차이점이 있다.

1. interface는 상속 가능

interface는 extends라는 키워드를 통해 상속의 개념을 사용할 수 있다
type에서 이를 구현하려면 & 연산자를 사용해야 한다.

2. 프로퍼티 축적 가능

interface의 또 다른 특징으로는 프로퍼티들을 축적시킬 수 있다는 것이다.

interface User {
    name: string
}

interface User {
    lastName: string
}

interface User {
    health:number
}

const hyewon: User = { 
    name: "hyewon",
    lastName:"han",
    health: 10
}

이러한 것을 type으로는 할 수 없다.

결론 : 오브젝트의 모양을 알려줄 때는 인터페이스를 쓰고, 나머지 경우에는 타입을 써야겠다!

profile
느리더라도 조금씩, 꾸준히

0개의 댓글