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:
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)
How can I make ReturnT
optional?
This not working:
<ErrorT, ReturnT = void>
<ErrorT, ReturnT = any>
<ErrorT, ReturnT = unknown>
<ErrorT, ReturnT extends void>
<ErrorT, ReturnT extends any>
<ErrorT, ReturnT extends unknown>
ReturnT
is no longer automatically output from a function.
This not working too:
const wrap = <ErrorT, ReturnT = void>(func: () => ReturnT): ReturnT extends void ? ReturnType<typeof func> : ReturnT => {
return func()
}
What to do?
Unfortunately, you either provide all generic arguments or none in this case. To mitigate this usually an additional "factory" function is used:
const makeWrapper = <ErrorT,>() => <ReturnT,>(func: () => ReturnT) => func();
const wrap = makeWrapper<Error>();
const q = wrap(() => 22)