type alias 와 interface 둘 중 어떤 것을 쓰는게 좋을까?
타입스크립트는 0.8 버전부터 시작해서 굉장히 급속도로 많은 버전들이 나오기 시작했다.
그래서 초창기에는 type alias(type으로 줄여 말하기도 함)와 interface는 많이 달랐고 interface가 할 수 있는 것들이 더 많았다.
그래서 예전부터 배웠던 사람들은 interface를 여기저기서 남발하는 경향이 있는데 이렇게 모든 곳에서 interface를 쓰는 것은 좋지 않은 습관이다.
type과 interface는 엄연히 다른 문법이고 성격도 특징도 다르다.
많은 곳에서 type과 interface를 교체해서 사용할 수는 있지만 interface를 마구 쓰는 것 보다는 정확하게 type과 interface가 어떻게 다른 지 어떤 곳에서 type을 쓰는게 맞고 어떤 곳에서 interface를 쓰는게 맞는지 정확하게 알고 있는 것이 중요하다.
우선 PositionType이라는 type과 PositionInterface라는 interface를 만들어보았다.
type PositionType = {
x: number;
y: number;
};
interface PositionInterface {
x: number;
y: number;
}
object
type과 interface는 object
형태로 만들 수 있다.
// object
const obj1: PositionType = {
x: 1,
y: 1,
};
const obj2: PositionInterface = {
x: 1,
y: 1,
z: 1,
};
class
type과 interface는 class
형태로 구현할 수 있다.
// class
class Pos1 implements PositionType {
x: number;
y: number;
}
class Pos2 implements PositionInterface {
x: number;
y: number;
}
extends
type은 intersection을 이용해서 두가지 타입을 묶을 수 있다.
type ZPositionType = PositionType & { z: number };
interface는 extends를 이용해 확장을 할 수 있다.
사실 타입스크립트 초창기에는 type을 이용해서 확장하는 것은 불가능했고 type을 이용해서 할 수 없는 것들이 많았다.
type은 유틸리티나 map타입, index타입 같은 computer properties
를 사용할 수 있다.
type Person = {
name: string;
age: number;
};
type Name = Person['name']; // string
type NumberType = number;
type Direction = 'left' | 'right'; // Union Type
}
type과 interface는 언뜻보면 굉장히 비슷해 보이지만, 이러한 차이점이 있다.
이러한 차이점들은 타입스크립트가 업데이트 될때마다 조금씩 바뀌어 왔다.
사실 초창기버전에는 type과 interface가 할 수 있는게 많이 달랐지만, 갈수록 많이 비슷해지고 있다.