0

I am creating a helper function to create async reducers. I want to create a method which takes in a record (object) of functions, and returns a fully typed result.

Here is a short version of what I have so far:

const typed = <T extends keyof any>(
  asyncActions: Record<T, (...args: any[]) => Promise<unknown>>
) => asyncActions;

const result = typed({
  func: (praram: string) => Promise.resolve(),
  func2: (praram: number) => Promise.resolve(),
});

The resulting type of result is: const result: Record<"func" | "func2", (...args: any[]) => Promise<unknown>>.

As you can see the keys of the return value are being infered correctly, but I cannot work out how to force the infer of the functions. Is this at all possible? Or am I barking up an extremely tall tree?

1 Answer 1

4

The type of the properties in asyncActions is widened to (...args: any[]) => Promise<unknown> because it is annotated as such, where the only thing the compiler can infer is K, the keys. Instead you might want to just annotate the type of asyncActions as a generic type T which is constrained to Record<keyof T, (...args: any[]) => Promise<unknown>>:

const typed = <T extends Record<keyof T, (...args: any[]) => Promise<unknown>>>(
    asyncActions: T
) => asyncActions;

const result = typed({
    func: (praram: string) => Promise.resolve(),
    func2: (praram: number) => Promise.resolve(),
});

/* const result: {
    func: (praram: string) => Promise<void>;
    func2: (praram: number) => Promise<void>;
} */

As you see, the type of result is now reasonably strong, and the compiler knows specifically what the parameters of each property will be:

result.func("hello"); // okay
result.func(123); // error
result.func2(123); // okay
result.func2("hello"); // error

as well as the return types:

result.func("hello").then(v => v.toUpperCase()) // error!
// ----------------------------> ~~~~~~~~~~~
// Property 'toUpperCase' does not exist on type 'void'.

Playground link to code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.