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?
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?
Share Improve this question edited Mar 17 at 12:20 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked Mar 17 at 11:58 Алексей СоснинАлексей Соснин 532 silver badges5 bronze badges1 Answer
Reset to default 2Unfortunately, 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)