Suppose there is a function defined as follows:
type FooParams<Params extends unknown[], Result> = {
name: string,
request: (...params: Params) => Promise<Result>
}
const foo = <Params extends unknown[], Result>(params: FooParams<Params, Result>) => {
// do stuff
}
Now imagine there are a couple of requests and a collection called "store" that holds these requests:
interface Todo {
id: number;
title: string;
}
const getTodos: () => Promise<Todo[]> = () => Promise.resolve([{ id: 2, title: 'clean' }]);
const getTodo: (id: number) => Promise<Todo> = (id: number) => Promise.resolve({ id, title: 'clean' });
const requestStore = {
getTodo: {
name: 'getTodo',
request: getTodo,
},
getTodos: {
name: 'getTodos',
request: getTodos,
},
} as const;
The objective now is to generate "foo"-functions for each request in the store.
While adding them manually with specific keys works:
// Works
foo(requestStore['getTodo'])
Attempting to add them dynamically like this does not work:
// Does not work. Error message:
// Type '(() => Promise<Todo[]>) | ((id: number) => Promise<Todo>)' is not assignable to type '() => Promise<Todo[]>'.
// Type '(id: number) => Promise<Todo>' is not assignable to type '() => Promise<Todo[]>'.(2322)
const createFooFromStore = (requestName: keyof typeof requestStore) => () => {
const { name, request } = requestStore[requestName]
foo({ name, request })
}
Is there an alternative approach to rewrite this so that a foo-function can be created for every entry in the "requestStore"?
Here is a link to a playground with the sample code:
In the playground example, the error message is displayed at the bottom for the "request" parameter.