如何推断泛型函数的返回类型
我有一个总是返回一个类型的函数,虽然它可以改变并手动定义它会是一些工作并且不可扩展,所以我试图通过使用打字稿的 infer
来实现这一点关键字
I have a function that will always return a type, though it can change and defining it by hand would be some work and not scalable, so I'm trying to achieve this by using typescript's infer
keyword
起初我看到了这个reddit帖子使用
type Foo<T> = T extends { a: infer U, b: infer U } ? U : never;
type T10 = Foo<{ a: string, b: string }>; // string
type T11 = Foo<{ a: string, b: number }>; // string | number
问题是,我的类型是一个泛型函数
Problem is, my type is a generic function
这是一个最小的例子,
const fnFromLib = <T>(a: string, b: Record<string, string>) => {
return function barFn(c: T) {
return {
c,
b: b[a],
};
};
};
const foo = <T>(a: Record<string, string>) => {
return {
bar: fnFromLib<T>('foo', a),
};
};
type returnTypeInferer<T> = T extends (a: Record<string, string>) => infer U ? U : never;
type fooType = typeof foo;
type fooReturnType = returnTypeInferer<fooType>;
没有错误,但是,由于没有传递泛型类型,fooReturnType
将被推断为
there are no errors, but, since there was not a generic type being passed, fooReturnType
will be inferred as
type fooReturnType = {
bar: (c: unknown) => {
c: unknown;
b: string;
};
}
注意到 fnFromLib 中的 T 不是从参数推断的,应该在函数调用中传递我尝试将类型参数从 fooReturnType
传递到 fooType
,但是给我一个解析错误
Noting that T from fnFromLib is not inferred from arguments and should be passed in the function call I try to pass on a type argument from fooReturnType
to fooType
, but that gives me a parsing error
type returnTypeInferer<T> = T extends (a: Record<string, string>) => infer U ? U : never;
type fooType<T> = typeof foo<T>; // ------ parsing error: ';' expected ---------
type fooReturnType<T> = returnTypeInferer<fooType<T>>;
有什么方法可以实现我想要的吗?
Is there a way I can achieve what I want?
谢谢
通过将函数包装到泛型类中来设法做到这一点
Managed to do it by wrapping the function into a generic class
class GnClass<T> {
foo = (a: Record<string, string>) => {
return {
bar: fnFromLib<T>('foo', a),
};
};
}
type returnTypeInferer<T> = T extends (a: Record<string, string>) => infer U ? U : never;
type fooType<T> = GnClass<T>['foo'];
type fooReturnType<T> = returnTypeInferer<fooType<T>>;
但我想坚持使用函数式编程,我不会将此标记为已接受的答案,暂时将使用它,因为我目前看不到其他替代方法,并且会喜欢另一种方法.
But I want to stick with functional programming, I will not mark this as accepted answer, will use it for now as I see no other alternative in the moment and would love another approach.