Search code examples
typescripttyping

Typescript I want a type which is the union of all types in an abject properties


I have this object

{
    "obj1" : type1;
    "obj2" : type2;
    "obj3" : type3;
    "obj4" : type4;
    "obj5" : type5;
}

I want to get a type like the following.

type MyType = type1 | type2 | type3 | type4 | type5;

I don't think the title of the question sound very good, If you would suggest a title for the question I would be grateful as well.


Solution

  • You can do this:

    interface A {
      obj1: number;
      obj2: string;
      obj3: boolean;
    }
    
    type MyType = A[keyof A];
    

    Where keyof A extracts the keys, you get "obj1" | "obj2" | "obj3". And then you can use it to index your record type A[k].