gpt4 book ai didi

javascript - 将两个功能合二为一

转载 作者:行者123 更新时间:2023-12-05 05:29:49 28 4
gpt4 key购买 nike

此处的目标是通过 参数组合 从 2 个函数创建一个函数。使用 JavaScript 可以轻松完成,但使用 typescript 并不容易。

结合这两个功能的一种方法是代理。示例:

const f1 = (a: number) => {
return (a + 1) * 2;
}

const f2 = (b: string, c: string[]) => {
c.push(b);
return c;
}

const combiner = (f1: Function, f2: Function) => {
return new Proxy(f1, {
apply(target, thisArg, args) {
const f1_args = args.slice(0, f1.length);
const f2_args = args.splice(f1.length);
f1(...f1_args);
f2(...f2_args);
}
});
};

const f = combiner(f1, f2);

f(1, 'foo', ['bar']); // Typehints?

问题是是否可以使用 typescript 键入 combiner 函数的类型提示结果?

最佳答案

通过使用两个通用类型 A1A2 来简单地键入组合函数的参数,它们保存两个函数的参数元组类型。

const combiner = <
A1 extends any[],
A2 extends any[]
>(f1: (...args: A1) => void, f2: (...args: A2) => void) => {
return new Proxy(f1, {
apply(target, thisArg, args) {
const f1_args = args.slice(0, f1.length);
const f2_args = args.splice(f1.length);
f1(...f1_args as A1);
f2(...f2_args as A2);
}
}) as unknown as (...args: [...A1, ...A2]) => void
};

我们只需要断言返回的类型是一个以组合的A1A2元组作为参数类型的函数。

const f = combiner(f1, f2);
// ^? const f: (a: number, b: string, c: string[]) => void

f(1, 'foo', ['bar']);

Playground

关于javascript - 将两个功能合二为一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74846386/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com