最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to declare optional type in TypeScript generics? - Stack Overflow

programmeradmin4浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 2

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)
发布评论

评论列表(0)

  1. 暂无评论