Type Aliases

Happhee·2022년 4월 25일
1

📘 TypeScript

목록 보기
9/10

✨ 타입 별칭

특정 타입이나 인터페이스를 참조할 수 있는 타입 변수이다.

예제로 알아보기

  • ✅ 간단한 타입 별칭
const apple: string = "apple";

type Fruit = string;
const orange: Fruit = "orange";
  • ✅ interface 타입 별칭
type Fruit = {
    name: string;
    color: string;
    quantity: number;
}
let mylike: Fruit = {
    name: "strawberry",
    color: "red",
    quantity : 12
}

mylike = {
    name: "orange",
    color: "orange"
}
/*
'quantity' 속성이 '{ name: string; color: string; }' 형식에 없지만 
'Fruit' 형식에서 필수입니다.ts(2741)
*/

타입 별칭을 사용해 인터페이스를 만들 수 있으며, 이에 대한 사용방식도 같다.
때문에 mylike라는 변수에 Fruit의 타입을 지정하면 속성이 모두 존재하지 않을 경우에는 오류를 나타낸다.

  • ✅ generic 타입 별칭
type Fruit<T> = {
    name: T,
    color: T,
    quantity : number
}
let mylike: Fruit<string> = {
    name: "strawberry",
    color: "red",
    quantity : 12
}
mylike = {
    name: "orange",
    color : 3
  // 'number' 형식은 'string' 형식에 할당할 수 없습니다.ts(2322)
}

위의 예제 코드를 제네릭으로 바꾼 코드이다. mylike의 제네릭을 string으로 정의했기 때문에 color에 number가 할당되면 오류를 발생시킨다.

특징

타입 별칭은 새로운 타입 값을 생성하는 것이 아니라 정의한 타입에 대한 참조를 쉽게 하기 위해서 부여하는 것이다.

  • ✅ interface로 선언
interface Dancer {
    name: string,
    age: number;
}
let dancer: Dancer;
/* 
class Dancer
interface Dancer
*/
  • ✅ 타입 별칭으로 선언
type Dancer = {
    name: string,
    age: number;
}
let dancer: Dancer;
/*
type Dancer = {
    name: string;
    age: number;
}
*/

❗️ interface vs type ❗️

위의 코드로 알 수 있듯이 인터페이스와 타입의 가장 큰 차이는 타입의 확장 가능 여부이다.
인터페이스는 타입 확장이 가능하지만, 타입 별칭은 확장이 불가능하다는 점을 기억해야 한다.


📚 학습할 때, 참고한 자료 📚

profile
즐기면서 정확하게 나아가는 웹프론트엔드 개발자 https://happhee-dev.tistory.com/ 로 이전하였습니다

0개의 댓글