一个变量类型允许是多个类型,如果访问某个类型的属性,编辑器会直接提示错误

比如 变量 tuple 可能为string 或 number 类型,如果直接访问tuple.toFixed

const mixedTupleTypeArray: (string|number)[] = ['hello', 2333]
const tuple = mixedTupleTypeArray[0];
// tuple 类型有可能是 string 或 number
// 编辑器会提示错误,Property 'toFixed' does not exist on type 'string | number'
if(tuple.toFixed){

}

即使加?操作符也不行,还是会提示错误

tuple?.toFixed

解决方法: typeof 判断类型后再访问,如下所示

if(typeof tuple === 'number'){
    tuple.toFixed
}
if(typeof tuple === 'string'){
    tuple.substring
}

如果是 class 类相关的继承模式呢?

比如

class Animal{

}

class Dog extends Animal{
    constructor(){
        super();
    }
    speak(){
        console.log('汪')
    }
}

const animal = new Animal();
const dog = new Dog();

const mixedClassTypeArray: (Animal|Dog)[] = [animal, dog];
const classItem = mixedClassTypeArray[0]
// 报错 Property 'speak' does not exist on type 'Animal | Dog'.
if(classItem.speak){

}

直接使用 classItem.speak 编辑器提示错误 Property 'speak' does not exist on type 'Animal | Dog'

两种写法可以解决

方法一
用 as 强行告诉编译器,classItem 属于 Dog 类

if((classItem as Dog)?.speak){

}

方法二
用 instanceof 判断实例化自哪里

if(classItem instanceof Dog){
    classItem.speak
}


转载入注明博客园池中物 willian12345@126.com sheldon.wang

github: https://github.com/willian12345