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

gigi·2022년 7월 11일
0

리터럴 타입

const userName = "Bob";  // const 재할당 불가 이처럼 정해진 string값을 가진것을 문자열 리터럴타입

let userName:string = "Tom";
userName = 3;  // 에러

let userName:string | number = "Tom";
userName = 3;

유니온타입

type Job = "police" | "developer" | "teacher";  // "|" 세로줄 => 유니온타입

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

const user : User = {
	name : "Bob",
	job: "police",
}
// 유니온 타입 (Union Types) [or]

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)             // 둘다 color가 있기때문에 에러가 안난다.
	gift.start()   // 에러
}

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

교차타입

// 교차타입 (Intersection Types) [and]

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개의 댓글