TypeScript #4 Literal/Union/Intersection types

2023. 3. 11. 15:29공부/TypeScript

Literal type

Literal 타입은 값 자체가 타입으로 사용됨. 즉, 해당 값과 정확하게 일치하는 타입을 가지게 됨. 

let greeting: "hello" = "hello";

위와 같이 'greeting' 이라는 변수는 문자열 'hello'만을 가지게 되며, 다른 문자열을 할당하면 타입에러가 발생 

타입 에러 발생

 

Union Types

 Union 타입은 '|' 연산자를 사용하여 둘 이상의 타입을 결합 할 수 있다.

//Union types
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();
    }
}

이 코드에서 getGift라는 함수는 gift라는 매개변수를 받으며 이 매개변수는 Car 또는 Mobile 타입 둘 중 하나일 수 있다.

                                                      

 

교차타입 (인터섹션 타입)

 

Intersection 타입은 & 연산자를 사용하여 둘 이상의 타입을 결합할 수 있습니다. 예를 들어, 인터페이스 Person 과 인터페이스 University를 합쳐서 새로운 객체 universityStudent를 만들려면 다음과 같이 작성할 수 있습니다.

//InterSection types
interface Person{
    name:string;
}

interface University{
    major:string;
    grade:number;
}

const universityStudent:Person&University = {
    name:"kim",
    major:"computer science",
    grade:1
};

 

'공부 > TypeScript' 카테고리의 다른 글

TypeScript #7 Utility type  (0) 2023.03.14
TypeScript #6 Generic  (0) 2023.03.12
TypeScript #5 Class  (0) 2023.03.12
TypeScript #3 Function  (0) 2023.03.11
TypeScript #1 Type  (0) 2023.03.10