Extracting From Deeply Nullable Types

We use GraphQL at work and one area that has always caused me a lot of pain is extracting a deeply nested, and deeply optional field from the GraphQL return type.

This results in having code that looks something like this:

type UserAddress = NonNullable<
  NonNullable<GetUsersQueryResult["data"]>["users"][0]
>["address"]

Not great.

So, with a bit of TypeScript magic from the internet, I created a Dig type that will dig through a type, handling null values automatically along the way. Here is what the result looks like:

type UserAddress = Dig<GetUsersQueryResult, 'data.users[].address'

The code to make this work is kind of, well no, really complex! I could explain it, but honestly it would take way too long for this short Byte, so I’ll let you explore it yourself to learn how it works!

type IndexedField<T> =
  T extends Array<infer U> ? NonNullable<U> : undefined

type Dig<T, P> =
  P extends `${infer Left}.${infer Right}` ?
    Left extends keyof T ? Dig<NonNullable<T[Left]>, Right>
    : Left extends `${infer FieldKey}[]` ?
      FieldKey extends keyof T ?
        Dig<IndexedField<NonNullable<T[FieldKey]>>, Right>
      : undefined
    : undefined
  : P extends keyof T ? NonNullable<T[P]>
  : P extends `${infer FieldKey}[]` ?
    FieldKey extends keyof T ?
      IndexedField<NonNullable<T[FieldKey]>>
    : undefined
  : undefined