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

Viewed 390

I'm blocked by a small problem:

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

I checked the type definitions of array.find and it does say it could possibly return undefined. Why is my environment saying the the foundFoo is of type string and not string | undefined?

The only other questions regarding this on StackOverflow that I found, asked pretty much the opposite why it "could" be undefined, so I'm not sure why my environment is saying the opposite.

1 Answers

Make sure you have strictNullChecks options enabled in your tsconfig.json file. When that option is not enabled, then all types (except for any) will basically resolve to 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)

Related