【问题标题】:Typescript infer generics within genericsTypescript 在泛型中推断泛型
【发布时间】:2020-07-23 23:52:14
【问题描述】:

问题

假设我有一个接口Wrapped

interface Wrapped<T> {
  data: T
}

我想定义一个这样的函数:

function f<T>(arg: any): T {
  const obj: Wrapped<T> = doSomethingAndGetWrappedObject<T>(arg)
  return obj.data
}

// Don't pay attention to the argument, it is not important for the question
const n: number = f<number>(/* ... */)

问题是,在我的应用程序中传递number 作为类型参数非常不方便,我想传递Wrapped&lt;number&gt;,即像这样调用f

const n: number = f<Wrapped<number>>(/* ... */)

问题是:如何输入f 使其成为可能?

我尝试过的

function f<T extends Wrapped<V>, V>(arg: any) {
  // ...
}
// Now this works, but it is very annoying to write the second type argument
const n: number = f<Wrapped<number>, number>() 
// I would like to do this, but it produces an error
// Typescript accepts either no type arguments or all of them
const n: number = f<Wrapped<number>>()
// This just works in an unpredictable way
function f<T extends Wrapped<any>>(
  arg: any
): T extends Wrapped<infer V> ? V : any {
  /* ... */
}

【问题讨论】:

标签: typescript generics typescript-generics


【解决方案1】:

您可以使用infer 关键字来创建用于提取泛型类型的辅助类型。

interface Wrapped<T> {
  data: T
}

type ExtractGeneric<T> = T extends Wrapped<infer X> ? X : never

function f<T extends Wrapped<any>>(): ExtractGeneric<T> {
  ....
}

const n = f<Wrapped<number>>()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-04
    • 2019-09-17
    • 2020-09-09
    • 2016-12-05
    • 2021-07-28
    • 2017-06-02
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多