一:联合类型:认为一个变量可能有两种或两种以上的类型。
用代码举个例子,声明两个接口Waiter(服务员)接口和Teacher(技师)接口,然后在写一个judgeWho(判断是谁)的方法,里边传入一个animal(任意值),这时候可以能是Waiter,也可能是Teacher。所以我们使用了联合类型,关键符号是|(竖线)。
interface Waiter {anjiao: boolean;say: () => {};}interface Teacher {anjiao: boolean;skill: () => {};}function judgeWho(animal: Waiter | Teacher) {}
二:类型保护
1、类型断言:通过断言的方式确定传递过来的准确值,但并不会不执行,只是不报错而已。
function judgeWho(animal: Waiter | Teacher) {if (animal.anjiao) {(animal as Teacher).skill();}else{(animal as Waiter).say();}}
2、in语法
function judgeWhoTwo(animal: Waiter | Teacher) {if ("skill" in animal) {animal.skill();} else {animal.say();}}
3、typeof,判断具体数据类型之后才做处理。
type sn = string | numberfunction fn(a: sn, b: sn){if(typeof a === 'string' || typeof b === 'string'){return `${a}${b}`}return a+b}
4、instanceof,只能用于保护对象类型。
class NumberObj {count: number;}function addObj(first: object | NumberObj, second: object | NumberObj) {if (first instanceof NumberObj && second instanceof NumberObj) {return first.count + second.count;}return 0;}
