TypeScript - 리터럴, 유니온, 교차 타입

oong·2022년 8월 11일
0

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

const userName1 = "Bob"; // const: 변경 불가능한 변수
let userName2: string | number = "Tom"; // let: 변경 가능한 변수
userName2 = 3;

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

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

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

interface HighSchoolStudent {
    name: number | string;
    grade: 1 | 2 | 3;
}

Union Types (유니온 타입)

동일한 속성의 타입을 구별해서 다르게 할 수 있다.

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

interface Mobile {
    name: "mobile";
    color: string;
    call(): void;
}
// 동일한 속성의 타입을 구별해서 다르게 할 수 있는 것 -> Union
function getGift(gift: Car | Mobile) {
    console.log(gift.color);
    if (gift.name === "car") {
        gift.start();
    } else {
        gift.call();
    }
}

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,
}

1개의 댓글

comment-user-thumbnail
2022년 8월 11일

내친구 개과천선 ~ ^_^

답글 달기

관련 채용 정보