给定一个函数类型F,我想创建一个新的类型,该类型在F之前是“可组合的”,这意味着它接受并返回与F相同的参数。例如:
const stringToNumber = (s: string) => s.length;
const stringToString: ComposableOn<(s: string) => number> = (s: string) => s + s;
const composedResult = stringToNumber(stringToString('a'));
但是,我无法正确定义类型ComposableOn
。这是我尝试过的事情:
type ComposableBefore<F extends (...args: any) => any> = (args: Parameters<F>) => Parameters<F>;
type StoN = (s: string) => number;
const sToS: ComposableBefore<StoN> = (s: string) => s + s; // error: the type is [string] => [string] and not string => string
type ComposableBefore<F extends (...args: any) => any> = Parameters<F> extends Array<infer U>? (...args: Parameters<F>) => U: never;
const complex: ComposableBefore<(a: string, b: number, c: { d: number, e: string }) => number> = (a, b, c) => c; // not good either, since it can return a value of any type of the original function's argument types.
正确的键入方式是什么?
答案 0 :(得分:1)
您可以使用...
直接在函数签名中扩展Parameters
。至于return,由于要支持多个参数,因此return类型应该是一个元组,因此您将需要扩展函数的返回:
const stringToNumber = (s: string) => s.length;
const stringToString: ComposableBefore<(s: string) => number> = (s: string) => [s + s];
const composedResult = stringToNumber(...stringToString('a'));
type ComposableBefore<F extends (...args: any) => any> = (...args: Parameters<F>) => Parameters<F>;
type StoN = (s: string) => number;
如果这是常见的用例,您还可以考虑为单参数函数添加一种特殊的情况:
const stringToNumber = (s: string) => s.length;
const stringToString: ComposableBefore<(s: string) => number> = (s: string) => s + s;
const composedResult = stringToNumber(stringToString('a'));
const multiStringToNumber = (s: string, s2: string) => s.length + s2.length;
const multiStringToString: ComposableBefore<typeof multiStringToNumber> = (s: string, s2: string) => [s + s, s2 + s2];
const multiComposedResult = multiStringToNumber(...multiStringToString('a', 'b'));
type ComposableBefore<F extends (...args: any) => any> =
F extends (a: infer U) => any ? (...args: Parameters<F>) => U :
(...args: Parameters<F>) => Parameters<F>;