我不知道如何摆脱这个错误,我也不知道为什么它谈论 null。
seo?.breadcrumbs || []
不应该已经涵盖了breadcrumbs
为空的情况吗?
但是在介绍提案中,如果我这样做
as SEOPostTypeBreadcrumbs[]
,那么它就解决了问题,但我觉得这不是解决方案。
编辑:看起来它抱怨
breadcrumbs
数组中的项目可以是 null
?
这是由 Wordpress GraphQL 工具自动生成的 graphql-codegen
TS2322: Type 'Maybe<{ __typename?: "SEOPostTypeBreadcrumbs" | undefined; }
& Pick<SeoPostTypeBreadcrumbs, "text" | "url">>[]' is not assignable to type 'SeoPostTypeBreadcrumbs[]'.
Type 'Maybe<{ __typename?: "SEOPostTypeBreadcrumbs" | undefined; } & Pick<SeoPostTypeBreadcrumbs, "text" | "url">>'
is not assignable to type 'SeoPostTypeBreadcrumbs'.
Type 'null' is not assignable to type 'SeoPostTypeBreadcrumbs'.
intro.tsx(28, 5): The expected type comes from property 'breadcrumbs' which is declared here on type 'IntrinsicAttributes & IntroProps'
seo
类型:
export type CptNeighborhoodFragment = { __typename: 'CptNeighborhood' } & {
seo?: Maybe<
{ __typename?: 'PostTypeSEO' } & Pick<
PostTypeSeo,
| 'metaDesc'
| 'metaKeywords'
| 'metaRobotsNofollow'
| 'metaRobotsNoindex'
| 'opengraphAuthor'
| 'opengraphDescription'
| 'title'
> & {
breadcrumbs?: Maybe<
Array<
Maybe<
{ __typename?: 'SEOPostTypeBreadcrumbs' } & Pick<
SeoPostTypeBreadcrumbs,
'text' | 'url'
>
>
>
>;
}
>;
};
用途:
<Intro
title={seo?.title || ''}
breadcrumbs={seo?.breadcrumbs || []}
/>
介绍道具
interface IntroProps {
title: string;
breadcrumbs?: SeoPostTypeBreadcrumbs[];
}
SeoPostType面包屑
export type SeoPostTypeBreadcrumbs = {
__typename?: 'SEOPostTypeBreadcrumbs';
text?: Maybe<Scalars['String']>;
url?: Maybe<Scalars['String']>;
};
您可以在代码生成配置中将 avoidOptionals 设置为 true,以防止嵌套的 Maybe 包装器出现在输出代码中
您还可以将 Maybe 类型的值从 T | null
(默认)修改为您想要的任何值;
T | null | undefined
,也许吧。