如何获得可选字段的子项
How get to a child of an optional field
我有这种类型:
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;
};
在我的代码中,我需要获取作者字段
但我不知道如何在不创建像 Array<{ __typename?} 这样的自定义类型的情况下键入和管理它。在我的代码中,我尝试了:
let authors:weeklyArticleDto['authors'];
这使我的 VS 和 ts playground 中出现错误:
type weeklyArticleDto = GetWeeklyArticleQuery['weeklyArticle'];
const weeklyArticle: weeklyArticleDto = data.weeklyArticle;
let authors:weeklyArticleDto['authors'];
if (weeklyArticle) {
authors = weeklyArticle.authors;
}
如何解决?
您可以为此使用 built-in NonNullable<Type>
utility type。
let authors: NonNullable<weeklyArticleDto>['authors'];
我有这种类型:
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;
};
在我的代码中,我需要获取作者字段 但我不知道如何在不创建像 Array<{ __typename?} 这样的自定义类型的情况下键入和管理它。在我的代码中,我尝试了:
let authors:weeklyArticleDto['authors'];
这使我的 VS 和 ts playground 中出现错误:
type weeklyArticleDto = GetWeeklyArticleQuery['weeklyArticle'];
const weeklyArticle: weeklyArticleDto = data.weeklyArticle;
let authors:weeklyArticleDto['authors'];
if (weeklyArticle) {
authors = weeklyArticle.authors;
}
如何解决?
您可以为此使用 built-in NonNullable<Type>
utility type。
let authors: NonNullable<weeklyArticleDto>['authors'];