typescripttypescript-typingstypescript-genericstypescript-utility

Utility types that converts each member of an object type


How can I create a type Promises<T> where T is an object, such that the new type has all the same members of T, and for each member of type T[key] we have instead the type Promise<T[key]>?


Solution

  • You can do this with a mapped type:

    type Promises<T extends object> = { [K in keyof T]: Promise<T[K]> }
    

    Let's test it out:

    interface Foo {
      a: string;
      b: number;
      c: boolean;
    }
    
    type PromisesFoo = Promises<Foo>;
    /* type PromisesFoo = {
        a: Promise<string>;
        b: Promise<number>;
        c: Promise<boolean>;
    } */
    

    Looks good.

    Playground link to code