本书未发布
类型守护
用 类型断言 来做类型保护
function animal(animalName: Bird | Dog) { if (animalName.fly) { // 类型断言 (animalName as Bird).sing() } else { (animalName as Dog).bark() } }
用 in 来做类型保护
function animalSecond(animalNameSecond: Bird | Dog) { if ('sing' in animalNameSecond) { animalNameSecond.sing() } else { animalNameSecond.bark() } }
用 typeof 来做类型保护
function add(n1: string | number, n2: string | number) { if (typeof n1 === 'string' || typeof n2 === 'string') { return `${n1}${n2}` } return n1 + n2 }
使用 interface 来做类型保护
class NumberObj { public count: number constructor(count: number) { this.count = count } } function addSecond(first: object | NumberObj, second: object | NumberObj) { if (first instanceof NumberObj && second instanceof NumberObj) { return first.count + first.count } return 0; }