TypeScript:Array.find 实际上可能是未定义的,但它作为固定类型返回

jos*_*ias 4 type-inference typescript

我被一个小问题所困扰:

const foo = ["foo", "bar"]; // type "string[]"
const foundFoo = foo.find(fooEl => fooEl === "notFooBar"); // type "string" -> why not "string | undefined"
Run Code Online (Sandbox Code Playgroud)

我检查了类型定义array.find,它确实说它可能返回未定义。为什么我的环境说 is foundFooof typestring而不是string | undefined

我在 StackOverflow 上发现的与此相关的唯一其他问题几乎提出了相反的问题,为什么它“可能”未定义,所以我不确定为什么我的环境说相反的内容。

Ter*_*rry 7

确保您的文件中strictNullChecks启用了选项tsconfig.json。当该选项未启用时,所有类型(除了any)基本上都会解析为T | undefined

在严格的空检查模式下,nullundefined值并不在每种类型的域中,只能分配给它们自己 和any(一个例外是 undefined 也可以分配给void