본문 바로가기

TypeScript

타입과 인터페이스 차이.

type PlayerA = {
    name:string
}
//타입의 상속방법
type PlayerAA = PlayerA & {
    lastName : string
}
const playerA:PlayerAA = {
    name:"harim",
    lastName:"chi"
}
/////
interface PlayerB {
    name:string
}
//인터페이스 상속방법
interface PlayerB{
    lastName:string
}
//인터페이스는 중복으로 사용가능
interface PlayerB {
    health : number
}
const playerB: PlayerB ={
    name : "nico",
    lastName:"choi",
    health:100
}

인터페이스가 좀더 상속하기 좋다 중복으로 이름 해서 사용해도 됨

 

Type Aliases과 Interfaces의 차이점

Type Aliases과 인터페이스는 매우 유사하며 많은 경우 자유롭게 선택할 수 있습니다.

인터페이스의 거의 모든 기능은 type에서 사용할 수 있으며, 주요 차이점은 type을 다시 열어 새 속성을 추가할 수 없는 것입니다.

반면 인터페이스는 항상 확장 가능합니다.

결론: 대부분의 경우 개인 취향에 따라 선택 가능
(인터페이스 사용을 조금 더 추천)