【发布时间】:2020-06-09 12:24:29
【问题描述】:
我的问题:我的问题的一个最小示例是 (typescript play example with the code):
enum Keys { foo = "foo", bar = "bar" }
function getValue<A extends Keys, B>(dict: { [K in A]?: B }, key: A): B | null
{
const result = dict[key]
if (result !== undefined) {
return result
} else {
return null
}
}
Typescript 对语句 return result 给出以下类型检查错误:
Type 'B | undefined' is not assignable to type 'B | null'.
Type 'undefined' is not assignable to type 'B | null'.
我的问题:为什么类型保护result !== undefined 在上面的示例中不起作用,我该如何解决?
我的尝试:
- 当我检查https://www.typescriptlang.org/play/index.html 中的示例时,我看到变量
result的类型为{ [K in A]?: B | undefined; }[A]。但是我预计打字稿可以自动将其减少到B | undefined。也许我在A或dict的类型声明中有错误,因此打字稿无法减少查找类型... - 当前的夜间版本
3.9.0-dev.20200224也会出现该错误。 - 将类型保护更改为
typeof(result) !== "undefined"没有帮助。
【问题讨论】:
标签: typescript dictionary types type-conversion lookup