Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: Reference subtype of a nullable type definition

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"]>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading