TS를 사용하면 타입을 사용하는 변수와 별도로 타입을 정의할 수 있다.
Aliases(별칭) 및 Interfaces(인터페이스)를 사용하면 서로 다른 변수/객체 간에 타입을 쉽게 공유할 수 있다.
타입 별칭을 사용하면 사용자 지정 이름(별칭)으로 타입을 정의할 수 있다.
유형 별칭은 string
과 같은 기본 타입이나 object
및 array
와 같은 더 복잡한 타입에 사용할 수 있다.
type CarYear = number
type CarType = string
type CarModel = string
type Car = {
year: CarYear,
type: CarType,
model: CarModel
}
const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla"
const car: Car = {
year: carYear,
type: carType,
model: carModel
};
인터페이스는 객체 타입에만 적용된다는 점을 제외하면 타입 별칭과 유사하다.
interface Rectangle {
height: number,
width: number
}
const rectangle: Rectangle = {
height: 20,
width: 10
};
인터페이스는 서로의 정의를 Extending(확장)할 수 있다.
인터페이스를 확장한다는 것은 원본과 동일한 속성에 새로운 것을 더한 새 인터페이스를 만든다는 뜻이다!
interface Rectangle {
height: number,
width: number
}
interface ColoredRectangle extends Rectangle {
color: string
}
const coloredRectangle: ColoredRectangle = {
height: 20,
width: 10,
color: "red"
};