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

소이뎁·2023년 8월 5일
0

TypeScript-코딩앙마

목록 보기
5/8
post-thumbnail

🌈 코딩앙마의 TypeScript 강좌 수강 후, 이해한 내용을 정리한 글입니다.

리터럴 타입(Literal Types)

let/var가 아닌 const로 선언된 변수는 특정 string/number 타입(리터럴)으로 지정된다.

const userName1 = "Bob"; // "Bob" type
let userName2 = "Tom"; // string type

유니온 타입(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(); // Car type
    } else {
       	gift.call(); // Mobile type
    }
}

교차 타입(Intersection Types)

기존 object 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,
};

0개의 댓글