更有用的打字稿字典类型:警告访问的项目可能未定义

More useful typescript dictionary type: warn accessed item could be undefined

我想在访问字典时收到警告,提示该值可能未定义。但是我仍然希望在设置值或通过 Object.values() 访问值时进行类型检查。 TypeScript 中是否有任何类型具有这些属性,或给出该错误的配置选项?

type AlwaysPresent = {[id: string]: Date }

type PotentiallyUndefined = {[id: string]: Date | undefined }


const a: AlwaysPresent = {}
// good, no error
Object.values(a).filter(date => date.getTime())
// bad, no error, we have actually no assurance there is an item in the dictionary
console.log(a["2"].getTime())
// good, correctly errors
a["1"] = undefined


const b: PotentiallyUndefined = {}
// bad, errors - this is too cautious for my use case
Object.values(b).filter(date => date.getTime())
// good, correctly errors, we have no assurance there is an item in the dictionary and this correctly warns of such an event
console.log(b["2"].getTime())
// bad, no error, this is too lax as setting undefined should not be allowed
b["1"] = undefined

您可能对启用 TypeScript 4.1 中引入的 the --noUncheckedIndexedAccess compiler flag 感兴趣。这会导致您的原始 AlwaysPresent 类型按照您想要的方式运行,至少对于您的示例代码而言:

type AlwaysPresent = {[id: string]: Date }

const a: AlwaysPresent = {}
// good, no error
Object.values(a).filter(date => date.getTime())
// good, error
console.log(a["2"].getTime())
// good, correctly errors
a["1"] = undefined

请注意,此编译器选项未包含在 the --strict compiler flag 中(并且其名称不以 strict 开头),因为这种行为虽然对某些代码库来说是可取的,但确实会使某些操作不太方便.使用 --strict 打开它最终会为现有代码库引发大量误报警告(具体来说,数组上的许多 for 循环将开始抱怨可能 undefined 值)。

Playground link to code