类型保护
JS typeof操作符 在运行时 返回一个值的基本类型,可以使用typeof 收缩类型的判断
function printAll(strs:string|string[]|null){if(typeof strs === 'object'){for(const s of strs){console.log(s)}}else if(typeof strs === 'string'){console.log(strs)}else{//dothing}}
通过typeof 确定 不同类型下的处理结果, 但此时还会有一个警告, strs 可能是null, 这就需要用到 真值收窄
真值收窄
通过JS的隐式转换 来确定一个表达式的true 和false,我们也可以用来去判断一个值是否存在
function printAll(strs:string|string[]|null){if(strs && typeof strs === 'object'){for(const s of strs){console.log(s)}}else if(typeof strs === 'string'){console.log(strs)}else{//dothing}}
function printAll(strs:string|string[]|null){if(typeof strs === 'object'){for(const s of strs!){console.log(s)}}else if(typeof strs === 'string'){console.log(strs)}else{//dothing}}
in收窄
type Fish = { swim: () => void };type Bird = { fly: () => void };function move(animal: Fish | Bird) {if ("swim" in animal) {return animal.swim();// (parameter) animal: Fish}return animal.fly();// (parameter) animal: Bird}
类型判断式
function isFish(pet: Fish | Bird): pet is Fish {return (pet as Fish).swim !== undefined;}let pet = getSmallPet();//此时Ts还会自动推导else中的pet 是Birdif (isFish(pet)) {pet.swim(); // let pet: Fish} else {pet.fly(); // let pet: Bird}
