Home > other >  Array.find (and other similar methods) does not implicitly return `undefined`
Array.find (and other similar methods) does not implicitly return `undefined`

Time:04-06

Array.prototype.find must return T | undefined.

But for some reason in my (automatically generated NestJS) environment TypeScript implicitly has only T as the return type of such methods.

How should I make TypeScript automatically inferr that find must return T | undefined?

CodePudding user response:

Take a look at strictNullChecks compiler option: https://www.typescriptlang.org/tsconfig#strictNullChecks

When strictNullChecks is false, null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.

When strictNullChecks is true, null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.

CodePudding user response:

Is this what you are looking for?

const task: Task | undefined = this.tasks.find((task) => task.id === id);
  • Related