I'm dealing with a complex data structure that is deeply nested, and I need to reference a type within it. The issue is that this type doesn't have its own unique name or definition. Here's an example:
MyQuery['system']['errors']['list'][number]
I generate the MyQuery
type automatically from a graphql query using graphql-codegen. I'm trying to determine the type of a single error
, but I face two challenges:
- All intermediate values are nullable.
- I lack a distinct identifier for the error in my auto-generated types.
I've attempted the following solutions:
- This method works, but it's difficult to read:
type Error = NonNullable<NonNullable<NonNullable<MyQuery>['system']>['errors']>['list'][number]
- This approach doesn't work (
?.['field']
also fails)
type Error = MyQuery?['system']?['errors']?['list']?[number]
- This solution works, but introduces unnecessary variables:
const error = queryResult?.system?.errors?.list?.[0]
type Error: typeof error
- Although somewhat effective, this method results in non-null fields inside Error, which is not desired
import { DeepNonNullable } from 'utility-types'
type Error = DeepNonNullable<MyQuery>['system']['errors']['list'][number]
In essence, I am seeking a simpler way to implement "optional chaining for types" in TypeScript. Given that my API contains a lot of null values, it would be incredibly beneficial if there was a more straightforward approach than using multiple NonNullable<T>
statements.