Home > Net >  Undefined not propagating as possible function return type, void works
Undefined not propagating as possible function return type, void works

Time:09-06

In a shared DB library written by a long-departed senior dev we have two helper functions

/** Helper function to return *exactly* one result. */
export declare const one: <T>(a: T[]) => T;
/** Helper function to return zero or one result. */
export declare const first: <T>(a: T[]) => T | undefined;

The former works fine, but the undefined part of the union in the latter doesn't seem to work, instead being ignored by the type-checker when compiling. When we replace it with void, we see expected errors where there has been an assumption that it will return <T>.

I understand that there is a difference between undefined and void based on Why does TypeScript have both `void` and `undefined`?, since the function also throws errors when you replace the undefined with basically any other type, but undefined seems to be uniquely ignored.

This playground shows the error, but I'm not seeing the error when the module is imported in my repo. Under what circumstances would the TS compiler ignore an undefined value in a union function return type?

CodePudding user response:

I think you're running your code in non-strict mode, which is fine, but maybe you're not aware of it.

In the playground you can uncheck all the strict options under TS Config > Type Checking and then I also see no error.

I would advise to turn on strict mode. Your project might suddenly give a lot of errors. Consider turning on the strict options one by one until you've migrated all your code.

  • Related