// 리터럴 타입
const userName1 = "Bob";
let userName2: string | number = "Tom";
userName2 = 3;
- userName1같이 하나의 문자열을 넣은 형태로 정의되어 있는 타입을 문자열 리터럴 타입이라 한다.
type Job = 'police' | 'developer' | 'teacher';
interface User {
name: string;
job: Job;
}
const user: User = {
name: 'Bob',
job: 'developer',
};
interface HighSchoolStudent {
name: string;
grade: 1 | 2 | 3; // union 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();
} else {
gift.call();
}
}
- 만약에 if문으로 구분을 지어주지 않고 gift.start()이렇게 사용할 경우 Mobile속성에는 start()가 없기 때문에 error가 발생
// intersection types
interface Car {
name: string;
start(): void;
}
interface Toy {
name: string;
color: string;
price: number;
}
const toyCar: Toy & Car = {
name: 'toyCar',
start() {},
color: 'black',
price: 1000,
};
- 교차 타입은 교차하고자 하는 interface의 모든 속성을 기입해야 error가 발생하지 않는다.