使用联合类型,只会提示共有的方法
解决联合类型的几种方式:
对 in 语法的理解
instanceof 语法
interface Bird {fiy: boolean;sing: () => {};}interface Dog {fiy: boolean;bark: () => {};}// 解决联合类型的几种方式:// 类型断言的方式function trainAnial(animal: Bird | Dog) {if (animal.fiy) {(animal as Bird).sing();} else {(animal as Dog).bark();}}// in 语法来做类型保护function trainAnialSecond(animal: Bird | Dog) {if ("sing" in animal) {animal.sing();} else {animal.bark();}}// typeof 语法来做类型保护function add(first: number | string, second: number | string) {if (typeof first === "string" || typeof second === "string") {return `${first}${second}`;}return first + second;}// instanceof 语法来做类型保护(只有class才具备用instanceof操作符class NumberObj {count!: number;}function addSecond(first: object | NumberObj, second: object | NumberObj) {if (first instanceof NumberObj && second instanceof NumberObj) {return first.count + second.count;} else {return 0;}}
