跳至主要內容

TypeScript

chanchaw大约 1 分钟react

错误与提示

动态访问对象属性报错

通过 a[propName] 的方法动态访问对象属性时,vscode 会报错:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MenuItem'.
  No index signature with a parameter of type 'string' was found on type 'MenuItem'

解决方法看 接口定义对象类型 ,参看文档 对象的任意属性open in new window

数据类型

定义数组

定义函数

元组与交叉类型

接口定义对象类型

下面代码的32行表示动态类型,增加兼容性。重要用处是当动态调用对象属性时保证 vs code 不报错。例如:a[propName] 其中的 propName 是变量,表示动态获取对象 a 不同的属性数据,此时如果没有第32行代码则会报错:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MenuItem'.
  No index signature with a parameter of type 'string' was found on type 'MenuItem'

接口与type定义函数

keyof,typeof,in