스파르타코딩클럽 내일배움캠프 Typescript 강의를 들으며 공부한 것을 적은 것입니다.
function printId(id: number | string) {
}
이때 만약 id 에 toUpperCase() 를 사용한다면?
function printId(id: number | string) {
console.log(id.toUpperCase());
// error
// string 형식에는 toUpperCase를 사용할 수 있지만,
// number 형식에는 없다.
}
따라서, type narrowing! 타입을 좁혀주는 작업을 해주는게 좋다.
function printId(id: number | string) {
// type narrowing
if(typeof id === string) {
console.log(id.toUpperCase());
}
}
type Common = {
name: string,
age: number,
genter: string
}
type Animal = {
howl: string
}
type Cat = Common & Animal;
let cat: Cat = {
age: 5,
gender: 'female',
name: 'asher',
howl: 'mew mew'
}
결합이기 때문에 무조건 속성을 다 작성해 주어야 한다.