Edw*_*ssi 4 generics typescript typescript-generics
免责声明:过度简化的功能如下,我知道它们没用
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>不是有效的打字稿.
如何根据泛型获得具有不同返回类型的函数的返回类型?
我不妨把它放在一个答案中,虽然它看起来不会满足你的需求.TypeScript目前既没有通用值,也没有更高的kinded类型,也没有typeof任意表达式.TypeScript中的泛型在某种程度上是"浅薄的".所以据我所知,遗憾的是没有办法描述将类型参数插入泛型函数并检查结果的类型函数:
// doesn't work, don't try it
type GenericReturnType<F, T> = F extends (x: T) => (infer U) ? U : never
function thinger<T>(thing: T): T {
return thing;
}
// just {},
type ReturnThinger<T> = GenericReturnType<typeof thinger, T>;
Run Code Online (Sandbox Code Playgroud)
所以我能为你做的就是建议解决方法.最明显的解决方法是使用类型别名来描述thinger()返回的内容,然后将其用于多个位置.这是你想要的"向后"版本; 而不是从函数中提取返回类型,您从返回类型构建函数:
type ThingerReturn<T> = T; // or whatever complicated type you have
// use it here
declare function thinger<T>(thing: T): ThingerReturn<T>;
// and here
interface ThingHolder<T> {
thing: ThingerReturn<T>;
}
// and then this works
const myThingHolder: ThingHolder<{ a: string }> = {
thing: thinger({ a: "lol" }),
};
Run Code Online (Sandbox Code Playgroud)
这有帮助吗?我知道这不是你想要的,但希望它至少是你前进的可能途径.祝好运!
| 归档时间: |
|
| 查看次数: |
827 次 |
| 最近记录: |