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;
}
동일한 속성의 타입을 구별해서 다르게 할 수 있다.
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();
}
}
교차 타입은 여러 개의 타입을 하나로 합쳐 주는 역할을 한다.
interface Car {
name: string;
start(): void;
}
interface Toy {
name: string;
color: string;
price: number;
}
const toyCar: Toy & Car = {
name: "타요",
start() {},
color: "blue",
price: 1000,
}
내친구 개과천선 ~ ^_^