본문 바로가기

Language/Typescript

[Typescript] 리터럴, 유니온/교차 타입

728x90
반응형

literal type

const userName1 = "Bob";
let userName2 = "Tom";

userName2 = 3;  // Error

userName1의 타입은 "Bob"이고 username2의 타입은 string이다. const로 선언한 값은 바꿀 수 없으므로 "Bob" 이외의 값은 가질 수 없다. 반면 userName2는 언제든 다른 값으로 바뀔 수 있으니 보다 넓은 개념의 string 타입으로 정의된다. userName2의 타입을 명시하지 않았지만 다른 타입으로 바꾸면 에러가 발생한다. 

 

userName1처럼 정해진 string 값을 가진 것을 문자열 리터럴 타입이라고 한다. 

type로 비슷한 형태를 만들 수 있다.

type Job = "police" | "developer" | "teacher";

interface User {
    name : string;
    job : Job;
}

const user:User = {
    name : "Bob",
    job : "developer"
}

user 객체의 job에는 Job 타입에 정의된 값만 들어갈 수 있다.

 

 

union type

interface Car{
    name: "car";
    color: string;
    start(): void;
}

interface Mobile{
    name: "mobile";
    color: string;
    call(): void;
}

function getGift(gift: Car | Mobile){
    console.log(gift.color);
    if(gift.name === "car"){
        gift.start();
    } else{
        gift.call();
    }
}

유니온 타입은 여러 타입 중 하나가 될 수 있는 값을 의미한다. Car | Mobile은 값의 타입이 Car 또는 Mobile이 될 수 있음을 의미한다.

start()는 Car에만 있는 속성이고 call()은 Mobile에만 있는 속성이다. 두 개의 인터페이스에 동일한 이름의 속성(name)을 지정하고 값을 다르게 지정하여 if문으로 구분해서 사용할 수 있다. 이렇게 동일한 속성의 타입을 다르게 해서 구분할 수 있는 것을 식별 가능한 유니온 타입이라고 한다.

 

 

Intersection Types

interface Car{
    name: string;
    start(): void;
}

interface Toy{
    name: string;
    color: string;
    price: number;
}

const toyCar: Toy & Car = {
    name: "타요",
    start() {},
    color: "blue",
    price: 1000,
}

유니온 타입이 or의 의미였다면 교차 타입은 and를 의미한다. Toy & Car 타입은 Toy와 Car의 속성을 모두 가져야한다. Toy와 Car의 속성 중 하나라도 빠지면 에러가 발생한다.

728x90
반응형

'Language > Typescript' 카테고리의 다른 글

[Typescript] 제네릭(Generics)  (0) 2022.02.21
[Typescript] 클래스(Class)  (0) 2022.02.20
[Typescript] 함수  (0) 2022.02.18
[Typescript] 인터페이스(interface)  (0) 2022.02.17
[Typescript] 기본 타입  (0) 2022.02.17