Search code examples
typescripttypescript-types

Get/extract the type of a type that is one of the types in a union type - typescript


Given a union Type that exists in a generated file:

    export type UnionedType = {a: number; ...otherProps;} | {b: string; ...otherProps;};

How can the Types of each of the inline types be extracted? That is, how can a type be declared for {a: number; ...otherProps;} and a type for {b: number; ...otherProps;} given that the inline member {a: number; ...otherProps;} will always have a prop called "a", and the inline member {b: number; ...otherProps;} a prop called "b".

Each time "UnionedType" is generated, it would be ideal to have the possible types extracted: like type A = {[outputOfSomeTypeMagic <P , UnionedType>]};, such that after the magic type A = {a: number; ...otherProps;}.


Solution

  • @Aleksey L. accurately pointed out that I was just describing the purpose of the TypeScript global Extract utility.

    Answer: Use the Extract utility to extract each of the members, so you can reference them by name. Simply pass in the "UnionedType" and an interface that matches the member you want to extract:

    //export type UnionTypeOfAB = { a: {}; id: number } | { b: {}; id: number };
    import {UnionTypeOfAB} from './generated.ts';
    
    interface A {
      a: {};
    }
    
    interface B {
      b: {};
    }
    
    type A_Type = Extract<UnionTypeOfAB, A>; 
    // can use an inline interface instead of declaring one:
    //type A_Type = Extract<UnionTypeOfAB, {a:{}}>;
    
    /*A_type result:
     type A_Type = {
      a: {};
      id: number;
    } */
    
    type B_Type = Extract<UnionTypeOfAB, B>;
    /*B_type result:
     type B_Type = {
      b: {};
      id: number;
    } */