typescript 解决变量多类型访问属性报错--工作随记
一个变量类型允许是多个类型,如果访问某个类型的属性,编辑器会直接提示错误
比如 变量 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!