如何解决更有用的打字稿字典类型:警告访问的项目可能未定义
我想在访问字典时收到警告,该值可能未定义。但是,我仍然希望在设置值或通过 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,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
值)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。