I'm using graphql-codegen which has generated the following type:
type GetMenuQuery = {
__typename?: "RootQuery"
menu?: {
__typename?: "Menu"
id: string
menuItems?: {
__typename?: "MenuToMenuItemConnection"
nodes: Array<{
__typename?: "MenuItem"
id: string
url?: string | null
label?: string | null
childItems?: {
__typename?: "MenuItemToMenuItemConnection"
nodes: Array<{
__typename?: "MenuItem"
id: string
url?: string | null
label?: string | null
childItems?: {
__typename?: "MenuItemToMenuItemConnection"
nodes: Array<{
__typename?: "MenuItem"
id: string
url?: string | null
label?: string | null
childItems?: {
__typename?: "MenuItemToMenuItemConnection"
nodes: Array<{
__typename?: "MenuItem"
id: string
url?: string | null
label?: string | null
}>
} | null
}>
} | null
}>
} | null
}>
} | null
} | null
}
I'm fetching the data in my Layout component and I want to pass only the menu.menuItems.nodes
object to a Header component. In the Header component, I want to type the props. I will be ensuring it's not null before passing it to Header (i.e. {menu?.menuItems?.nodes && <Header menuItems={menu.menuItems.nodes}
).
I can't just set the type of the props as { menuItems: GetMenuQuery["menu"]["menuItems"]["nodes"] }
because each level is nullable.
I could do { menuItems: NonNullable<NonNullable<GetMenuQuery["menu"]>["menuItems"]>["nodes"] }
but this will be happening with many components and sometimes even deeper than this example.
Is there a better way of doing this? I'm hoping for some sort of utility that can accept any number of arguments and recursively make them NonNullable, but I'm admittedly beyond my knowledge here.
The end result I'm imagining would be to use it as such: { menuItems: NullBeGone<GetMenuQuery, ["menu", "menuItems", "nodes"]> }
where it iterates through the second argument (array) and performs NonNullable<T, array[i]>
and the T on each subsequent iteration is the result of the previous iteration.
{ menuItems: NonNullable<NonNullable<GetMenuQuery["menu"]>["menuItems"]>["nodes"] }
This will get really ugly really fast.