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

TypeScript: Array.find could actually be undefined but it is returned as a fixed type

我被一个小问题挡住了:

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

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

我在 Whosebug 上发现的与此相关的唯一其他问题几乎完全相反,为什么它“可能”未定义,所以我不确定为什么我的环境说的是相反的。

确保您的 tsconfig.json 文件中有 strictNullChecks options enabled。如果未启用该选项,则所有类型(any 除外)基本上都会解析为 T | undefined:

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void)