Typescript

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

sian han 2022. 12. 3. 22:08

※ Literal Types 리터럴 타입

 const userName1 = "Bob"; //Bob 타입
 let userName2 = "Tom"; // string 타입

userName1 은 string 타입 이지만 const 라서 "Bob" 이외에는 값을 가질 수 없다.  => 문자열 리터럴 타입 이라고 한다.

userName2 은 현재 Tom 이지만, 다른 값도 가질 수 있으니 string 타입을 갖는다.

 

만약 userName2  가 추후에 string 이 아니라 number 타입을 갖고 싶다면 ?

let userName2 : string | number = "Tom"; // 유니온타입

이렇게 명시해주면 된다.

 

 

▶ 문자열 리터럴 타입

type Job = "police" | "developer" | "teacher"; //리터럴 타입 정의

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

const user : User = {
	name : "Bob",
    job : "student"//Error : job 프로퍼티는 위에서 선언한 string 만 사용가능하다
    				// => job 리터럴 타입
}

 

▶ 숫자형 리터럴 타입

interface HighSchoolStudent{
	name : string;
    grade : 1 | 2 | 3; // 유니온타입
}

 

 

※ 유니온 타입

 

▷ 식별가능한 유니온 타입

 - 동일한 속성의 타입을 다르게 해서 구분하는 것을 식별가능한 유니온 타입이라고 한다.

interface Car{
	name: "car";
    color : stirng;
    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();
    }
}

 

 

 

※ 교차타입 Intersection Types

  - 교차타입은 여러 타입을 합친 것을 말한다.

 

  • 유니온 : A | B = or
  • 교차 : A && B = and
interface Car{
	name : string;
    start(): void;
}

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

const toyCar : Toy & Car = { //Toy 와 Car 을 합쳐서 ToyCar
	name : "타입",
    start() {},
    color : "blue",
    price: 1000,
};

각 인터페이스가 갖고 있는 속성을 모두 적어주어야 한다.