2

I've got a bunch of generated types (via GraphQL codegen) that look like this:

type X = {
  a?: Maybe<number>
  b?: Maybe<Array<MyType> | MyType>
  c?: Maybe<MyType2>
  d?: Maybe<Array<MyType3> | MyType3>
}

// Maybe is:
// type Maybe<T> = T | null | undefined;

For fields b and d, the codegen does the right thing according to GraphQL spec (see this issue) but in my specific codebase, I need to transform all the types to basically this:

type X2 = {
  a?: Maybe<number>
  b?: Maybe<Array<MyType>>
  c?: Maybe<MyType2>
  d?: Maybe<Array<MyType3>>
}

How to write a type utility that does this?

(Manually, it would be done like this:)

type X2 = Omit<X, 'b' | 'd'> & {
  b?: Maybe<Array<MyType>>;
  d?: Maybe<Array<MyType3>>;
};
1
  • For this to be a minimal reproducible example it would be nice to see some explicit definitions of your MyTypes. I don't want to write something up and find out that MyType3 extends Array<MyType2> or something weird like that.
    – jcalz
    Feb 8, 2021 at 16:57

1 Answer 1

3

It's a bit tricky to tease union members apart from each other, and I'm not 100% sure about the general use case, but here's one way you might approach it:

type Xform<T> = {
  [K in keyof T]: T[K] extends Maybe<infer V> ?
  Extract<V, Array<any>>[number] extends infer R ?
  T[K] extends Maybe<Array<R> | R> ?
  Maybe<Array<R>>
  : T[K] : T[K] : T[K]
}

type X2 = Xform<X>;
/* type X2 = {
    a?: Maybe<number>;
    b?: Maybe<MyType[]>;
    c?: Maybe<MyType2>;
    d?: Maybe<MyType3[]>;
} */

Basically what I'm doing is: for each key K in the keys of T, I'm checking the property value T[K]. If any of my tests fail I will just return the property value unchanged as T[K]. The tests I'm performing: is T[K] assignable to Maybe<V> for some V? If so, find any members of a union V that are Array<any> and get their element type, and save it into a new type parameter R (for convenience). Then finally: is T[K] assignable to Maybe<Array<R> | R>? If so, then return Maybe<Array<R>>. So we're looking for properties of the form Maybe<Array<XYZ> | XYZ> and converting them to Maybe<Array<XYZ>>, otherwise we're leaving them alone.

It's always possible that edge cases will pop up; if any of the types MyType or XYZ are themselves arrays or if you have unions of other things (e.g., Maybe<MyType[] | MyType2>), but hopefully this at least gives you some direction.

Playground link to code

1
  • This is fantastic, and seems to work great for the graphql-code-generator use case. Thank you! Feb 8, 2021 at 18:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.