如何从接口访问嵌套的可选索引

2023-11-29

鉴于以下接口描述这个TS游乐场

export type GetTestimonialsSectionQuery = { 
  __typename?: 'Query', 
  testimonialsSection?: { 
    __typename?: 'TestimonialsSection', 
    id: string, 
    testimonials: Array<{ __typename?: 'Testimonial', id: string, text: string, author?: { __typename?: 'TestimonialAuthor', id: string, name: string, photo: { __typename?: 'Asset', url: string } } | null }> 
} | null };

我想访问testimonials整个界面的索引通过使用索引访问类型,但是,当strictNullChecks设置了编译器选项,结果是any

Since testimonials can be undefined,在访问嵌套属性之前是否需要进行类型检查?


您只能执行以下形式的索引访问T[K] when K绝对是一个关键类型K;也就是说,当K extends keyof T. If T is a 联合型那么唯一确定的键T这些钥匙都存在于联盟的每个成员身上。那是,keyof (A | B | C)变成(keyof A) & (keyof B) & (keyof C).

就你而言,自从GetTestimonialsSectionQuery['testimonialsSection']是一个对象类型与两者的联合null and undefined,你将不被允许使用任何不是 key 的东西来索引它null and undefined... and null and undefined没有钥匙;你根本无法索引它们。因此出现错误:

type Bad = GetTestimonialsSectionQuery[
    'testimonialsSection']['testimonials'] // error!
// ----------------------> ~~~~~~~~~~~~~~
// Property 'testimonials' does not exist on type ...

如果您关心的只是对象类型而不是null and undefined,您可以使用实用程序类型将联合过滤为仅对象类型,然后再对其进行索引。一般来说,您可以通过以下方式过滤联合the Exclude<T, U>实用型,但对于删除的特定和常见情况null and undefined, 您可以使用the NonNullable<T>实用型:

type Testimonials = NonNullable<
    GetTestimonialsSectionQuery['testimonialsSection']
>['testimonials']
/* type Testimonials = {
    __typename?: "Testimonial" | undefined;
    id: string;
    text: string;
    author?: {
        __typename?: "TestimonialAuthor" | undefined;
        id: string;
        name: string;
        photo: {
            __typename?: 'Asset';
            url: string;
        };
    } | null | undefined;
}[] */
type Testimonials = NonNullable<
    GetTestimonialsSectionQuery['testimonialsSection']
>['testimonials']
/* type Testimonials = {
    __typename?: "Testimonial" | undefined;
    id: string;
    text: string;
    author?: {
        __typename?: "TestimonialAuthor" | undefined;
        id: string;
        name: string;
        photo: {
            __typename?: 'Asset';
            url: string;
        };
    } | null | undefined;
}[] */

看起来不错!

Playground 代码链接

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从接口访问嵌套的可选索引 的相关文章