Operator '+' cannot be applied to types 'string | number' and 'number' 해결 방법
-> Narrowing / Assertion
함수에서 Type이 아직 하나로 확정되지 않았을 경우 사용한다.
function 함수(x: number | string){
if (typeof x === 'string'){
return x + '1';
} else {
return x + 1;
}
}
서로 다른 속성을 가질 때
type Fish = { swim: string };
type Bird = { fly: string };
function 함수(animal: Fish | Bird){
if ('swim' in animal) {
return animal.swim
}
return animal.fly
}
배타적인 속성이 없을 때
type Car = {
wheel : '4개',
color : string
}
type Bike = {
wheel : '2개',
color : string
}
function 함수(x: Car | Bike){
if (x.wheel === '4개'){
console.log('the car is' + x.color);
} else {
console.log('the bike is' + x.color);
}
}
변수명 as string
as 키워드는 union type 같은 복잡한 타입을 하나의 정확한 타입으로 줄이는 역할
-> 기존 number 타입을 as string 하면 에러남
타입 쉴드 임시 해제용
-> return (x as number) + 1 결과를 number 타입처럼 계산해주지 않는다.
(as는 그냥 주장만 하는거지 실제로 타입을 바꿔주는건 아니기 때문)