I have some object with functions as values, something like this:
const service = {
methodA: (param1: TypeA, otherParam: string) => ({ a: 1 }),
methodB: (param1: TypeA, otherParam: number) => ({ b: 2 }),
}
What I'm trying to achieve is to have some generic function, that would pass the first parameter to each of those methods, creating new service with one less param in each method:
const serviceWithInjectedParam = injectFirstParam(someValue, service)
serviceWithInjectedParam.methodA(otherValue) // this should at the end call service.methodA(someValue, otherValue)
The thing is, that I cannot figure out typings for injectFirstParam
:( This is what I'm trying:
const injectFirstParam = <
S extends { [method: string]: (param1: TypeA, ...params: unknown[]) => unknown }
>(
param1: TypeA,
service: S
) => {
return (Object.keys(service) as (keyof S)[]).reduce((acc, key) => {
acc[key] = (...params: unknown[]) => service[key](param1, ...params) // what should be params type here? I have TS error here
return acc
}, {} as { [key in keyof S]: S[key] extends (param1: TypeA, ...params: infer P) => infer R ? (...params: P) => R : never })
}
but TS says that
Type '(...params: unknown[]) => unknown' is not assignable to type 'S[keyof S] extends (param1: TypeA, ...params: infer P) => infer R ? (...params: P) => R : never'.
and when I try to use injectFirstParam
I'm getting
Argument of type '{ methodA: (param1: TypeA, otherParam: string) => { a: number; }; methodB: (param1: TypeA, otherParam: number) => { b: number; }; }' is not assignable to parameter of type '{ [method: string]: (param1: TypeA, ...params: unknown[]) => unknown; }'.