![](/img/trans.png)
[英]Infer generic type argument from parameter type of function in TypeScript
[英]infer type argument from function argument in 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,这有助于将他们推向正确的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.