【问题标题】:Why is the generic type parameter T "unknown" in the return type? How can I type this function so that the return type is correctly inferred?为什么返回类型中的泛型类型参数 T “未知”?如何键入此函数以便正确推断返回类型?
【发布时间】:2021-06-23 15:07:06
【问题描述】:

打字稿手册 (https://www.typescriptlang.org/docs/handbook/2/generics.html#generic-constraints) 对通用约束进行了说明:

你可以声明一个受其他类型约束的类型参数 参数。

在这个人为的例子中,我怎样才能正确推断 wrap() 的返回类型中的“T”?


function wrap<T, F extends (() => T)>(cb: F): [T, F] {
  return [cb(), cb]
}

function load(): string {
  return ''
}

const [
  value, // unknown, should be string. Can I get typescript to infer this?
  wrapped, // () => string
] = wrap(load)

【问题讨论】:

  • 通用T 真的有必要吗?你可以使用ReturnType&lt;F&gt;link
  • 我认为最简单的表达方式是function wrap&lt;T&gt;(cb: () =&gt; T): [T, () =&gt; T] { return [cb(), cb] }

标签: typescript typescript-generics


【解决方案1】:

Typescript 在从 func&lt;T, F extends (() =&gt; T)&gt; 这样的构造推断 T 时遇到问题。在这种情况下,通常最好依赖infer。对于您的示例,我们可以使用实用程序类型 ReturnType,它在内部使用 infer 并完全满足我们的需要:

function wrap<F extends (() => any)>(cb: F): [ReturnType<F>, F] {
  return [cb(), cb]
}

function load(): string {
  return ''
}

const [
  value, // string
  wrapped, // () => string
] = wrap(load)

【讨论】:

    猜你喜欢
    • 2019-02-17
    • 2020-03-23
    • 2020-01-23
    • 1970-01-01
    • 2019-01-07
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多