I'm trying to assign to a property a type generated by the graphql-codegen
tool. The type I'm trying to assign is a nested type. Given the following type:
type SomeType = {
someKey: Maybe<
{ __typename?: "OtherType" | undefined } &
{ someNestedKey: ({ __typename?: "AnotherType" | undefined } & Pick<AnotherType, "prop1" | "prop2">)[] }
>
}
I need to be able to do:
myProperty: SomeType['someKey']['someNestedKey'] = []
However, the problem I'm running into is that the type of someKey
is a Maybe
type, so Typescript is complaining that there is no someNestedKey
property on the <Maybe { __typename?: "OtherType" | ...} & { someNestedKey: (...)[] }>
type (i.e., the type of someKey
).
In Typescript, you can use the !
method to state that you know for sure that the property value of a type that is union'ed with undefined
and/or null
does, in fact, exist in this case. Is there a way to do something similar when assigning a type?
Since I'm using the graphql-codegen
tool, I don't have control of these types.
I just found the answer in the documentation. I need to use the NonNullable
type.
myProperty: NonNullable<SomeType['someKey']>['someNestedKey'] = []
Reference: https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullablet