typescript - 获取使用泛型的函数的返回类型
问题描述
免责声明:过度简化的功能如下,我知道它们没用
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>
不是有效的打字稿。
如何获取基于泛型具有不同返回类型的函数的返回类型?
解决方案
尽管它看起来不能满足您的需求,但我不妨将其放在答案中。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" }),
};
这有帮助吗?我知道这不是你想要的,但希望这至少是你前进的一条可能的道路。祝你好运!
推荐阅读
- angular - 如何在工资字段中打印货币 $?我正在使用双向绑定
- python - 如何使用 For 循环在 Python 中更改列名
- excel - 循环工作表中的范围并更新另一个范围
- python - 为什么 FAST/ORB 在寻找图像边缘附近的关键点方面不好
- angular - 用 Observable 替换 Promise
- javascript - 如何完全防止 Web 表单输入文本项更改
- html - 缩放 500% 时 svg 路径移动
- javascript - React:如何将服务器端 HTML 与 React 组件和函数混合使用
- reactjs - 反应具有相同名称的元素
- c++ - 如何在 C++ 中制作表示整数的链表?(LeetCode 加两个数字)