Replace fields types in interfaces to promises

Viewed 350

Typescript has Partial<Object> type that helps to make the all fields of object optional.

Is it possible in the same way to create a generic type Promisify<Person> that will change the Person type from:

interface Person {
  getName(): string;
  getAge(): number;
}

to:

interface PromisifyPerson {
  getName(): Promise<string>;
  getAge(): Promise<number>;
}

I have an synchronous API described via Typescript interfaces and my goal is to create asynchronous version of API without rewriting the all interfaces what I have. This is another example:

interface ApplicationApi {
  startApp(): void;
  readFile(fileName): string; 
}

type AsyncApplicationAPI = Async<ApplicationApi>

after that I expect that AsyncApplicationAPI should be something like:

interface AsyncApplicationApi {
  startApp(): Promise<void>;
  readFile(fileName): Promise<string>; 
}
2 Answers

I'm sure you could create it, though it may take some work. You could simply create a function that would iterate over every property of the given object, and return an object that is identical except for the data members being wrapped in Promises, and the functions wrapped in new functions that return promises. Of course, you would have to worry about specifics, like if you wanted all of the objects properties' properties to be wrapped in promises or not...

edit: my answer would make it so you could pass an instance of an object and get a promisified instance back. You might not be able to do it for types in general from within the language itself.

type Promisified<T> = {
    [K in keyof T]: T[K] extends (...args: any) => infer R ? 
        (...args: Parameters<T[K]>) => Promise<R> :
        T;
}

Or see here.

Related