[英]Typescript infer generics within generics
Let's say I have an interface Wrapped
:假设我有一个
Wrapped
接口:
interface Wrapped<T> {
data: T
}
And I want to define a function like this:我想像这样定义一个 function :
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>(/* ... */)
The problem is, in my application it is very inconvenient to pass number
as type argument, I would like to pass Wrapped<number>
instead, ie to call f
like this:问题是,在我的应用程序中,将
number
作为类型参数传递非常不方便,我想传递Wrapped<number>
,即像这样调用f
:
const n: number = f<Wrapped<number>>(/* ... */)
The question is: how to type f
to make it possible?问题是:如何键入
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 {
/* ... */
}
You could create helper type for extracting the generic type by using infer
keyword.您可以使用
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>>()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.