typescript - 从打字稿中的函数参数推断类型参数
问题描述
我有这个游乐场和这段代码
export interface RemoteMethods<R> {
getAll: (url: string) => Promise<R>;
create: (url: string, model: R) => Promise<void>;
}
export type AsyncFunctionReturnType<
R,
Method extends keyof RemoteMethods<R>
> =
{
[key in Method]: RemoteMethods<R>[Method];
};
export const makeRemoteMethods = <R>(
) => {
return {
getAll: async (url: string) => {
return Promise.resolve(undefined);
},
create: async (url: string, model: R) => {
return Promise.resolve(undefined);
},
};
};
export const useAsyncCallback = <
R,
K extends keyof ReturnType<typeof makeRemoteMethods>
>(
method: K,
): AsyncFunctionReturnType<R, K> => {
const remoteMethods = makeRemoteMethods<R>();
const m = { [method]: remoteMethods[method] } as unknown as {
[key in K]: RemoteMethods<R>[K];
};
return {
...m,
};
};
const getAllSites = useAsyncCallback<{x: string}, 'getAll'>('getAll');
我想以某种方式推断此函数调用中的第二个类型参数
const getAllSites = useAsyncCallback<{x: string}, 'getAll'>('getAll');
我想调用如下函数:
const getAllSites = useAsyncCallback<{x: string}>('getAll');
并以某种方式推断类型参数K extends keyof ReturnType<typeof makeRemoteMethods>
解决方案
我相信这目前不可能直接实现,因为没有对泛型的部分推断,请参阅https://github.com/microsoft/TypeScript/issues/10571和https://github.com/microsoft/TypeScript/issues/20122(后者几乎是完全相同的代码)。可能有解决方法,但它们不会很好。
然而,对此的适当支持正在慢慢到来!https://github.com/microsoft/TypeScript/pull/26349是 TypeScript 的当前开放 PR,它允许您像这样调用您的函数:
const getAllSites = useAsyncCallback<{x: string}, _>('getAll');
此处_
表示您希望推断的通用变量,并且需要对该 var 进行正常推断行为(就像您看到的是否只有一个通用 arg,这是自动推断的)。
这尚未确认或合并 TypeScript 的行为,但如果您希望这样做,您可以 +1 该问题和 PR,这将有助于推动他们找到正确的解决方案。
推荐阅读
- javascript - 如何从 JavaScript 中的数字数组生成非重复随机数?
- ajax - 使用 axios get React 时状态不更新
- powershell - 如何从数组索引中命名文件?
- android - 如何在android中向动作栏发出警报
- php - 如何检查给定日期的预订时段
- mysql - 在mysql中插入X(从Z中选择Y)是否有更快的替代方法?
- iot - 如何通过我的网站控制我的 Arduino ESP8266 wifi 模块(来自 anywwre)
- sql - SQL Sum count of product by Member 和产品 YTD 的产品计数
- html - 元素内不同数量的 div 列的水平滚动
- postgresql - 我应该使用复合主键来加快 PostgreSQL 中基于时间戳的选择吗?