I order to abstract away common functionality it would be nice to have a function that takes a lambda as input and also its parameters.
The function should the be callable like
const lambdaFn = (param1: string, param2: number) => {
console.log(`Lambda - Param 1: ${param1}, Param 2: ${param2}`);
};
foo(lambdaFn, { param1: "test", param2: 1})
This would allow to call the function with its parameters. While they are passed as separate paremeters. The input params of the function would still have to match the pattern defined.
so far i came up with
function foo<T extends (...args: any[]) => void>(lambda: T, ...options: Parameters<T>): void {
lambda(...options);
}
with allows to call
foo(lambdaFn, 'test', 1);
and
type Params<T extends (...args: any[]) => any> = {
[K in keyof Parameters<T>]: Parameters<T>[K];
};
function foo<R, T extends (...args: any[]) => R>(lambda: T, options: Params<T>) {
lambda(...(Object.values(options) as Parameters<T>));
}
which allows to call
foo(lambdaFn, ['test', 2]);
However these do not match my expectation. since the first approach makes it hard to pass additional parameters at the end, e.g. config parameters. Providing an array like in the second one does not show the connection to the lambda in my opinion.
The ultimate goal of this is to create a custom hook for networks calls in react. where the lambda function internally should trigger a network request and the function parameters a are query params the body or other parts of the network call. the approach foo(lambdaFn, 'test', 1);
would be fine but is not usable if I would like to add a config parameter in the future.
foo(lambdaFn.bind(null, 'test', 1))
to sidestep the entire issue?foo(() => lambdaFn('test', 1))
. That just simplifies the design of callbacks massively.