我试图理解为什么 TypeScript 会给我以下错误:Object is possibly 'undefined'
这是代码片段:
const mergedDepsObj: { [key: string]: string } // Implementation here is not important
const results: Map<string, number> = new Map();
Object.keys(mergedDepsObj).forEach((key: string) => {
results.has(key) ? results.set(key, results.get(key) + 1) : results.set(key, 0);
})
基本上,当我尝试在 Map
(结果)中增加一个值时,我在这一行 results.set(key, results.get(key) + 1)
它不应该对我大喊大叫,因为我正在检查该值是否首先存在。 也许我错过了什么?
谢谢,
最佳答案
Map.has()
没有类型保护 See this issue或 this issue .
您可以通过回退 0
、-1
或您认为最适合您的代码的任何内容来解决此问题。
const mergedDepsObj: { [key: string]: string } = {}
const results: Map<string, number> = new Map();
Object.keys(mergedDepsObj).forEach((key: string) => {
results.has(key) ? results.set(key, (results.get(key) || 0) + 1) : results.set(key, 0);
})
自定义类型保护
但是,如上所述,我们在 this comment 的帮助下制作了自己的类型守卫.
interface Map<K, V> {
// Works if there are other known strings.
has<KnownKeys extends K, CheckedString extends K>(this: MapWith<string, V, any>, key: CheckedString): this is MapWith<K, V, CheckedString | KnownKeys>
has<CheckedString extends K>(this: Map<string, V>, key: CheckedString): this is MapWith<K, V, CheckedString>
}
interface MapWith<K, V, DefiniteKey extends K> extends Map<K, V> {
get(k: DefiniteKey): V;
}
const mergedDepsObj: { [key: string]: string } = {}
const results: Map<string, number> = new Map();
Object.keys(mergedDepsObj).forEach((key: string) => {
results.has(key) ? results.set(key, results.get(key) + 1) : results.set(key, 0);
})
我们可以在实际中看到它 here
关于javascript - TypeScript 报告对象可能是 'undefined' 而它不应该,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56977024/