amdilley
amdilley

Reputation: 271

Possible for mapped function types in typescript?

Say I have a function type in typescript

interface ParseFn {
  (param: string): number;
}

Is there a way to map function types in TypeScript? Can I do something like

type Async<T> = {
  [P in keyof T]: Promise<T[P]>;
}

const myAsyncNumParser: Async<ParseFn> = ...

?

Upvotes: 0

Views: 99

Answers (1)

jcalz
jcalz

Reputation: 330456

Mapped types in TypeScript completely ignore call and construct signatures, so they won't do what you want. Instead, you can use type inference in conditional types introduced in TypeScript 2.8. Assuming what you want is to take a function type T and return a new function type which takes the same parameters but whose return type is wrapped in Promise<>, you can do it like this:

type Async<T extends (...args: any) => any> =
    T extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : never;
type AsyncParseFn = Async<ParseFn>;
// type AsyncParseFn = (param: string) => Promise<number>

There are also predefined utility types called Parameters<T> and ReturnType<T> that use such conditional types to get the parameter tuple and return type of a function type. You could use those, instead, if you prefer:

type Async2<T extends (...args: any) => any> =
    (...args: Parameters<T>) => Promise<ReturnType<T>>;
type Async2ParseFn = Async<ParseFn>;
// type Async2ParseFn = (param: string) => Promise<number>

Either way should work. Okay, hope that helps; good luck!

Playground link to code

Upvotes: 1

Related Questions