联合类型和类型保护
类型保护在需要联合类型的时候才会出现或需要类型保护(类型守护)。
先创建两个接口
interface Student{
anjiao: boolean;
say: () => {
}
}
interface Teacher {
anjiao: boolean;
skill: () => {};
}
调用判断接口,所采用的类型守护方式(常用的有四种)
断言 as方式
function judgeWho(animal: Student| Teacher) {
if(animal.anjiao){
(animal as Teacher).skill()
}else{
(animal as Student).say()
}
}
in 方式
function judgeWhoTow(animal: Student| Teacher) {
if ('skill' in animal) {
animal.skill();
}else {
animal.say();
}
}
typeof方式
function add(first: string | number,second: string | number) {
if(typeof first === 'string' || typeof second === 'string') {
return `${first}${second}`;
}
return first + second;
}
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;
}