0

I am using graphql-codegen/typescript-apollo-angular to generate typescript code can be useed in our Angular application. We decided to enable strictNullChecks the only issue is that we use the following pattern to specify the types of inner nodes that are returned by the API:

type ListSomethingEdge = ListSomethingQuery["something"]["edges"][0];

In my case something is generated as a Maybe<Array<...>> which is correct. When I enable strictNullChecks the above code does not work anymore as something might be undefined / null as well.

Property 'edges' does not exist on type '({ __typename?: "SomethingConnection" | undefined; } & Pick<SomethingConnection, "totalCount"> & { edges?: Maybe<{ __typename?: "SomethingEdge" | undefined; } & { ...; }>[] | null | undefined; pageInfo: { ...; } & Pick<...>; }) | null | undefined'.ts(2339)

I was unable to find documentation on how to remove null / undefined types from a type alias like this. Maybe there is a different way to do this.

Jonas Osburg
  • 1,528
  • 1
  • 13
  • 16

1 Answers1

3

To remove null / undefined from the type you can use NonNullable utility.

NonNullable<T> constructs a type by excluding null and undefined from T

type ListSomethingEdge = NonNullable<ListSomethingQuery["something"]>["edges"][0];

Playground


NonNullable utility is built with conditional types

type NonNullable<T> = T extends null | undefined ? never : T

** You don't need to define it manually, typescript provides it and it is available globally.

Aleksey L.
  • 25,602
  • 7
  • 55
  • 64