typescript

How to declare optional type in TypeScript generics?


I want to make the ReturnT type optional and have it automatically inferred from the passed function

const wrap = <ErrorT, ReturnT>(func: () => ReturnT): ReturnT => {
  return func()
}

const q = wrap(()=> 22)

If I don't pass any parameters to the generic, everything works correctly:

enter image description here

But if I want to pass the ErrorT type as the first parameter to a generic, for example, the generic also asks for the second parameter:

const wrap = <ErrorT, ReturnT>(func: () => ReturnT): ReturnT => {
  return func()
}

const result = wrap<Error>(() => 22)

enter image description here

enter image description here

How can I make ReturnT optional?

This not working:

ReturnT is no longer automatically output from a function.

enter image description here

This not working too:

const wrap = <ErrorT, ReturnT = void>(func: () => ReturnT): ReturnT extends void ? ReturnType<typeof func> : ReturnT => {
  return func()
}

enter image description here

What to do?


Solution

  • Unfortunately, you either provide all generic arguments or none in this case. To mitigate this usually an additional "factory" function is used:

    Playground

    const makeWrapper = <ErrorT,>() => <ReturnT,>(func: () => ReturnT) => func();
    
    const wrap = makeWrapper<Error>();
    
    const q = wrap(() => 22)