noUncheckedIndexedAccess
选项,
当我们尝试使用任意键访问对象的属性时,值的类型就是您指定的任何类型,并且undefined
。
这种行为很好,因为它符合您在运行时可能遇到的情况,但是,
我希望能够指定没有办法确保每个属性访问都是安全的。
undefined
我尝试为自己寻找可能的解决方案,但没有成功。我想知道是否有办法在保留旗帜的同时做到这一点。
type ArbitraryStringIndexAccess = {
[key: string]: number
}
const object: ArbitraryStringIndexAccess = {}
const value: number = object.property
// Type 'number | undefined' is not assignable to type 'number'.
// Type 'undefined' is not assignable to type 'number'.
// (2322)
如果设置了检查,TS 无法推断这些值是安全的,并且无法针对特定情况禁用它。