Home > Back-end >  How get to a child of an optional field
How get to a child of an optional field

Time:02-23

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'];

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?

CodePudding user response:

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

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

Playground Link

  • Related