eslint-plugin-unicorn icon indicating copy to clipboard operation
eslint-plugin-unicorn copied to clipboard

Rule change proposal: `no-useless-undefined` add option to skip checking function body

Open Nkmol opened this issue 1 year ago • 1 comments

It is quite normal for a function to return T | undefined, for example with the Map.get() function. For this function it is also common to do some input checks, or return value checks, before doing something with the value. For these cases it also common to do an early exit with return, this is however conflicting with eslint/consistent-return.

Currently, the rule of no-useless-undefined would error in the following case:

declare const map: Map<number, string>;
function valueOrUndefined(value: number) {
  return map.get(0);
}

declare const input: number | undefined;
function readInput() {
  if(input === undefined) {
    console.error("Pick a valid input value.")
    return undefined;
  }

  return valueOrUndefined(input); // returns string | undefined
}

I believe it is good to let the user pick its preference in this case. Personally, I like return undefined in his case.


Related to https://github.com/sindresorhus/eslint-plugin-unicorn/issues/1199 Related PR: https://github.com/sindresorhus/eslint-plugin-unicorn/pull/2232/files

Nkmol avatar Feb 28 '24 16:02 Nkmol

How about a new option, such as checkReturn?

woody-li avatar Jun 03 '25 09:06 woody-li

I have another example similar to this:

type X = {
    foo: () => string | undefined
}

const x: X = {
    foo() {
        return undefined;
    },
}

If I keep the undefined, no-useless-undefined complains, if I remove it, typescript complains, that foo is not a void function.

syyyr avatar Jul 24 '25 10:07 syyyr