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

How get to a child of an optional field

I have this type:

export type GetWeeklyArticleQuery = {
    __typename?: 'Query';
    weeklyArticle?: {
        __typename?: 'WeeklyArticle';
        date: any;
        tags: Array<string>;
        title: string;
        authors: Array<{ __typename?: 'Author'; name: string; slug: string }>;
        bodyContent: { __typename?: 'RichText'; html: string };
        coverImage: {
            __typename?: 'Asset';
            url: string;
            title?: string | null;
            altText?: string | null;
            description?: { __typename?: 'RichText'; html: string } | null;
            caption?: { __typename?: 'RichText'; html: string } | null;
        };
        introLine: { __typename?: 'RichText'; html: string };
        footnote: Array<{ __typename?: 'RichText'; html: string }>;
    } | null;
};

In my code, I need to get the authors field
but I don’t know how to type and manage it without create a custom type like Array<{ __typename?}. In my code I tried:

let authors:weeklyArticleDto[‘authors’];

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

This gives me an error in my VS and in ts playground:

type weeklyArticleDto = GetWeeklyArticleQuery['weeklyArticle'];
const weeklyArticle: weeklyArticleDto = data.weeklyArticle;
let authors:weeklyArticleDto['authors'];
if (weeklyArticle) {
    authors  = weeklyArticle.authors;
}

How can fix it?

>Solution :

You can use the built-in NonNullable<Type> utility type for this.

let authors: NonNullable<weeklyArticleDto>['authors'];

Playground Link

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