如何编写一个允许任意索引访问且其值不可能未定义的类型?

问题描述 投票:0回答:1

如果我们启用 TypeScript 的

noUncheckedIndexedAccess
选项, 当我们尝试使用任意键访问对象的属性时,值的类型就是您指定的任何类型,并且
undefined

这种行为很好,因为它符合您在运行时可能遇到的情况,但是,
我希望能够指定没有办法确保每个属性访问都是安全的。

示例片段

undefined

我尝试为自己寻找可能的解决方案,但没有成功。
我想知道是否有办法在保留旗帜的同时做到这一点。


typescript
1个回答
0
投票

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 无法推断这些值是安全的,并且无法针对特定情况禁用它。

© www.soinside.com 2019 - 2024. All rights reserved.