问题描述
我被一个小问题所困扰:
const foo = ["foo","bar"]; // type "string[]"
const foundFoo = foo.find(fooEl => fooEl === "notFooBar"); // type "string" -> why not "string | undefined"
我检查了array.find
的类型定义,它确实说可能返回未定义的类型。为什么我的环境说foundFoo
是string
类型而不是string | undefined
类型?
我在StackOverflow上发现的与此有关的唯一其他问题几乎完全相反,为什么它“可能”未定义,所以我不确定为什么我的环境会说相反的话。
解决方法
确保[sum(i[1:]) for i in data]
文件中有strictNullChecks
options enabled。如果未启用该选项,则所有类型(tsconfig.json
除外)基本上都将解析为any
:
在严格的null检查模式下,
T | undefined
和null
值不在每种类型的域中,只能分配给它们自己和undefined
(一个例外是未定义是也可以分配给any
)