1. Literal Types
- 문자열 literal type: 정해진 string 값을 가짐
const username1 = "Bob"; //변할 수 없음, 문자열 literal type
let userName2 = "Tom" // 변할 수 있지만 string type으로 정의됨
userName2 = 3; // error
=> 가능하게 하려면
let userName2: string | number = "Tom";
예시 1)
type Job = "police" | "developer" | "teacher";
interface User {
name: string;
job: Job;
}
const user: User = {
name: "Bob";
~~ job: "student"; ~~ // error, Job type이 아님
job: "developer";
}
예 시 2)
interface HighSchoolStudent {
name: string;
grade: 1 | 2 | 3; // 숫자형 literal type
}
2. Union Types
- | (세로줄) = union type
- 식별 가능한 union type: 동일한 속성의 type을 다르게 해서 구분할 수 있는 것
interface Car {
name: "car"; // 타입의 값으로 "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") { // 식별 가능한 union type 사용, 검사할 항목이 많아지면 if 대신 switch문 사용
gift.start();
} else {
gift.call();
}
}
3. Intersection Types (교차 타입)
- 여러 type을 하나로 합쳐서 사용, & 를 의미
- 필요한 모든 기능을 가진 하나의 타입이 된다.
interface Car {
name: string;
start(): void;
}
interface Toy {
name: string;
color: string;
price: number;
}
const toyCar: Toy & Car = { // Toy 와 Car의 모든 속성을 다 기입해야함
name: "타요",
start(){},
color: "blue",
price: 1000,