首页 > 解决方案 > 获取使用泛型的函数的返回类型

问题描述

免责声明:过度简化的功能如下,我知道它们没用

function thinger<T>(thing: T): T {
    return thing;
}

const thing = thinger({ a: "lol" });

thing.a;

上面的代码编译得很好。但我需要将结果thinger<T>放入一个对象中。

interface ThingHolder {
    thing: ReturnType<typeof thinger>;
}

const myThingHolder: ThingHolder = {
    thing: thinger({ a: "lol" }),
};

但是我丢失了我的类型信息所以myThingHolder.thing.a不起作用

类型“{}”上不存在属性“a”

所以我尝试了以下

interface ThingHolder<T> {
    thing: ReturnType<typeof thinger<T>>;
}

const myThingHolder: ThingHolder<{ a: string }> = {
    thing: thinger({ a: "lol" }),
};

typeof thinger<T>不是有效的打字稿。

如何获取基于泛型具有不同返回类型的函数的返回类型?

标签: typescriptgenericstypescript-generics

解决方案


尽管它看起来不能满足您的需求,但我不妨将其放在答案中。TypeScript 目前既没有泛型值更高种类的类型,也没有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>;

所以我能为你做的就是建议解决方法。最明显的解决方法是使用类型别名来描述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" }),
};

这有帮助吗?我知道这不是你想要的,但希望这至少是你前进的一条可能的道路。祝你好运!


推荐阅读