1、应用场景
在使用vue3.0+ts 搭建的项目中,遇到如下错误

具体代码如下:
let subviewMenus = menusArr.filter((item)=> {
return item?.subview === config.subMenusId
// return item
})
2. 分析原因
经过尝试发现,在TypeScript环境中如果按JS的方式去获取对象属性,就会提示形如Property 'xxx' does not exist on type 'XXX'的错误。
这是因为Typescript在执行代码检查时,如果该对象没有定义相应属性的类型,就会产生该报错。
3. 解决办法
1. 将报错位置类型转为any(不推荐)
可以尝试将报错位置的代码类型,写成any类型,
let subviewMenus = menusArr.filter((item:any)=> {
return item?.subview === config.subMenusId
// return item
})
2. 用类型断言强制通过编译
用类型断言来强制通过TS的编译
(item] as any)
3.使用interface定义对象所有属性(推荐)
interface MenusTree {
route?: string |null,
label?: string |null,
subview?: string |null,
children?: object|null,
}
let subviewMenus = menusArr.filter((item:MenusTree)=> {
return item?.subview === config.subMenusId
// return item
})
网友评论