type Dog = {
name: string;
isBark: boolean;
};
type Cat = {
name: string;
isScratch: boolean;
};
type Animal = Dog | Cat;
//서로소 유니온 못한다고 가정
function warning(animal: Animal) {
if ("isBark" in animal) {
// 강아지
} else if ("isScratch" in animal) {
// 고양이
}
}
type Dog = {
name: string;
isBark: boolean;
};
type Cat = {
name: string;
isScratch: boolean;
};
type Animal = Dog | Cat;
function isDog(animal:Animal){
// 타입을 단언해서 좁힘
return animal.isBark !== undefined; // ❌오류
}
//서로소 유니온 못한다고 가정
function warning(animal: Animal) {
if ("isBark" in animal) {
} else if ("isScratch" in animal) {
}
}
→ 소괄호를 넣어 타입 단언
function isDog(animal:Animal){
return (animal as Dog).isBark !== undefined;
}
Animal
인것을 확인할 수 있음function isDog(animal:Animal): animal is Dog{
return (animal as Dog).isBark !== undefined;
}
Dog
타입이구나"라고 알아들음type Dog = {
name: string;
isBark: boolean;
};
type Cat = {
name: string;
isScratch: boolean;
};
type Animal = Dog | Cat;
function isDog(animal: Animal): animal is Dog {
return (animal as Dog).isBark !== undefined;
}
function isCat(animal: Animal): animal is Cat {
return (animal as Cat).isScratch !== undefined;
}
function warning(animal: Animal) {
if (isDog(animal)) {
animal;
} else if (isCat(animal)) {
animal;
}
}