프론트엔드/TypeScript
리터럴, 유니온/교차 타입
by alswlfl
2023. 1. 3.
리터럴 타입(Literal Types)
- const: 변하지 않는 값 선언 할 때
- let: 변할 수 있는 값 선언 할 때
- 문자열 리터럴 타입: 정해진 string 값을 가진 값
const userName1="Bob"; //문자열 리터럴 타입: 정해진 string값을 가진 값
let userName2="Tom";
let userName3:string | number="Tom"; //가질 수 있는 타입 명시 하기
type Job="police"|"developer" |"teacher";
interface User{
name:string;
job:Job;
}
const user: User = {
name:"Bob",
job:"developer",
};
유니온 타입(Union Types)
interface HighSchoolStudent{
name: number | string;
grade: 1|2|3;
}
// 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"){. //car인지 확인 한 후, 해당 메서드 출력
gift.start();
}else{
gift.call();
}
}
교차 타입(Intersection Types)
- 여러 개의 타입을 하나로 합쳐주는 역할
- 필요한 기능을 모두 가진 하나의 타입이 만들어짐
// Intersection 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,
}