From some code generate tool, I got some type definition similar to
type ParentType = {
viewer : {
userByUuid: {
username: string | null;
legalName: string | null;
} | null;
} | null;
}
And I want to be able to refer to the type similar to
type User = {
username: string | null;
legalName: string | null;
} | null;
I know if the ParentType is not nullable, I can use a way similar to
type User = ParentType['viewer']['userByUuid']
But how can I handle this type reference for the nullable type?
Thanks!
>Solution :
You can use conditional types to extract the non null part,
type ParentType = {
viewer : {
userByUuid: {
username: string | null;
legalName: string | null;
} | null;
} | null;
}
type NonNullableType<T> = T extends null ? never : T
type Viewer = NonNullableType<ParentType["viewer"]>
type User = NonNullableType<Viewer["userByUuid"]>