我正在try 在类型脚本中创建一个函数,该函数接受函数的对象文字,并返回具有非常相似签名的对象文字,只有第一个参数已被删除.这里的目标是完全保留类型,因为很容易返回对象文本,其中成员的函数的参数是未知的参数array.
目标如下:
const res = doSomething('someVal', { func1: (proxy, other: string) => proxy + other });
res.func1('other string') // This knows the "other" param is a string, and returns a string.
我可以创建一个编译的结果,但输出文字的函数都是参数数组,或者我得到了某种编译器错误.以下是我的众多try 之一.
type Proxy<T> = {
value: T;
};
/*
* The first parameter is always Proxy<T>.
* The remaining parameters are what I want to keep in the return function.
*/
export type ProxyMethod<T, F extends (signalProxy: Proxy<T>, ...args: readonly any[]) => any> =
F extends (...args: infer P) => infer R
? (args: P) => R
: never;
/** This is the type of the object literal of functions that is the input */
export type ProxyMethods<T, K extends string> = {
[Key in K]: ProxyMethod<T, (...args: unknown[]) => unknown>
};
/** Takes a ProxyMethod and creates a function without the first param. */
export type OutputMethod<F extends ProxyMethod<any, () => any>> =
F extends ProxyMethod<infer T, infer F2>
? F2 extends ((signalProxy: Proxy<T>, ...args: infer P) => infer R)
? (...args: P) => R : never
: never;
/** The intended output object literal */
export type OutputMethods<M extends ProxyMethods<any, string>> = { [Key in keyof M]: OutputMethod<M[Key]> };
function doSomething<T, const M extends Record<string, ProxyMethod<T, any>>>(
value: T,
methods: M
): OutputMethods<M> {
/* do something */
return methods as any; // stub, all I care about is the typings.
}
// Target signature provides too few arguments
doSomething('test', { help: (proxy: Proxy<string>, a: number) => `${a}`});