我已将我的对象对象输入为:
export interface ObjectInterface {
[key: string]: SomeOtherObjectInterface;
}
然后假设我有这样的对象:const obj: ObjectInterface = {
a: ...,
b: ...,
}
然后当我想访问某些对象属性时,它不是类型安全的:const x = obj.dsdssdsdsds;
我的 IDE 中没有错误。当我从
obj
中删除类型时它正确抛出错误。在这里可以做什么来使用我们的类型,但仍然会出现类似 Property 'dsds' does not exist on type......
的错误
最佳答案
typescript 4.1-beta
已经解决了这个问题。
这是一个新选项:--noUncheckedIndexedAccess
.
Turning on
noUncheckedIndexedAccess
will add undefined to any un-declared field in the type.
您可以在 TypeScript playground 上进行测试.
阅读更多:Announcing TypeScript 4.1 Beta - Pedantic Index Signature Checks (--noUncheckedIndexedAccess)
顺便说一下,数组也有同样的问题。如果按索引访问数组,即使该索引不存在,也不会出现任何 typescript 错误。幸运的是,这个选项也解决了数组问题。
附注
4.1
已发布 - read more about noUncheckedIndexedAccess
关于javascript - 当输入为 [key : string] 时,Typescript 不会检查对象属性是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64664734/