TS : interface 와 type 의 차이
type과 interface는 객체 타입의 이름을 지정하는 방법이다.
// interface
interface AnimalInterface {
species: string;
height: number;
weight: number;
}
const tiger: AnimalInterface = {
species: "tiger",
height: 200,
weight: 300,
};
// type
type AnimalType = {
species: string;
height: number;
weight: number;
};
const lion: AnimalType = {
species: "lion",
height: 180,
weight: 400,
};
확장하는 방법(상속)
interface
는 extends
로 상속하고, type
은 &
(특수문자)으로 상속한다.
선언적 확장
type
은 새로운 속성을 추가하기 위해 다시 같은 이름으로 선언할 수 없다.
// interface
interface Animal {
weight: number;
}
interface Animal {
height: number;
}
const tiger: Animal = {
weight: 100,
height: 200,
};
console.log(tiger);
// type
type _Animal = {
weight: number;
};
type _Animal = {//error : 식별자가 중복됨
height: string;
};
interface는 객체(Object)에서만 사용이 가능
interface는 리터럴 타입으로 확장할 수 없다.
interface AnimalInterface {
name: string
}
type AnimalType = {
name: string
}
type AnimalOnlyString = string
type AnimalTypeNumber = number
interface X extends string {} // 불가능
interface는 객체지향 프로그래밍의 개념을 활용해서 디자인되었고, type은 좀 더 유연하고 개방적이다.