0

I'm using graphql-code-generator to generate TypeScript definitions from my GraphQL queries and currently trying to extract a specific union from an array. Is this possible in TypeScript? I've found an example where someone extracted a type from a generic and tried to make use if the Extract function, but this does not work and returns just never:

export type Foo = Array<(
    {
      id: string;
      __typename: 'Data1'
    }
    | {
      id: string;
      __typename: 'Data2'
    }
  )>;

type MyQueryData1 = Extract<Foo, { __typename: "Data1"}>
type MyQueryData2 = Extract<Foo, { __typename: "Data2"}>

TypeScript Playground

Slevin
  • 4,268
  • 12
  • 40
  • 90
  • 1
    Check this :: https://stackoverflow.com/questions/45251664/typescript-derive-union-type-from-tuple-array-values/45257357 – Akhil Jun 30 '20 at 20:19

1 Answers1

1

Is this the result you want? ts playground

If so you have to extract the type from the deirved union type from the element values of the array,

type MyQueryData1 = Extract<Foo[number], { __typename: "Data1"}>
type MyQueryData2 = Extract<Foo[number], { __typename: "Data2"}>
subashMahapatra
  • 6,339
  • 1
  • 20
  • 26