新ReturnType的打字稿2.8是一个非常有用的功能,让你提取特定函数的返回类型.
function foo(e: number): number {
return e;
}
type fooReturn = ReturnType<typeof foo>; // number
Run Code Online (Sandbox Code Playgroud)
但是,我在泛型函数的上下文中使用它时遇到了麻烦.
function foo<T>(e: T): T {
return e;
}
type fooReturn = ReturnType<typeof foo>; // type fooReturn = {}
type fooReturn = ReturnType<typeof foo<number>>; // syntax error
type fooReturn = ReturnType<(typeof foo)<number>>; // syntax error
Run Code Online (Sandbox Code Playgroud)
有没有办法提取泛型函数给出特定类型参数的返回类型?
免责声明:过度简化的功能如下,我知道它们没用
function thinger<T>(thing: T): T {
return thing;
}
const thing = thinger({ a: "lol" });
thing.a;
Run Code Online (Sandbox Code Playgroud)
上面的代码转换得很好.但我需要将结果thinger<T>放入一个对象中.
interface ThingHolder {
thing: ReturnType<typeof thinger>;
}
const myThingHolder: ThingHolder = {
thing: thinger({ a: "lol" }),
};
Run Code Online (Sandbox Code Playgroud)
但是我丢失了我的类型信息,所以myThingHolder.thing.a不起作用
类型"{}"上不存在属性"a"
所以我尝试了以下内容
interface ThingHolder<T> {
thing: ReturnType<typeof thinger<T>>;
}
const myThingHolder: ThingHolder<{ a: string }> = {
thing: thinger({ a: "lol" }),
};
Run Code Online (Sandbox Code Playgroud)
但是typeof thinger<T>不是有效的打字稿.
如何根据泛型获得具有不同返回类型的函数的返回类型?