What is the proper overload for an undefined function argument?
04:20 22 Jul 2026

It's a matter of TypeScript, although the usage is with a React hook. That is, I must call the below function all the times.

Let's say I have a base class:

class B {
  foo(): void { }
}

Then, I have a hook where B is used as extension constraint:

function useMyHook(cb?: () => T): T | B {
  return cb ? cb(): new B();
}

In other words, I would like that:

  • when the argument is missing, the result is a new instance of B;

  • when the argument is undefined (or even null), also the result is a new instance of B;

  • when the argument is a function, the result has to be inferred from the function itself.

So far, I tried adding some overloads:

function useMyHook(): B;
function useMyHook(cb: undefined): B;
function useMyHook(cb: () => T): T;

However, when I try this:

class D extends B { }

let z: (() => D) | undefined;
const x = useMyHook(z);  //compile error

does not compile because there's no overload matching the case:

No overload matches this call.
  Overload 1 of 3, '(cb: undefined): B', gave the following error.
    Argument of type '(() => D) | undefined' is not assignable to parameter of type 'undefined'.
      Type '() => D' is not assignable to type 'undefined'.
  Overload 2 of 3, '(cb: () => D): D', gave the following error.
    Argument of type '(() => D) | undefined' is not assignable to parameter of type '() => D'.
      Type 'undefined' is not assignable to type '() => D'.

Is there any way to solve this problem?

typescript react-hooks overloading