代码之家  ›  专栏  ›  技术社区  ›  ruohola

如何将TypeScript的索引访问类型与可为空的类型一起使用?

  •  1
  • ruohola  · 技术社区  · 5 年前

    我试图用另一种类型来定义一种类型脚本类型。

    这项工作:

    type Result = { data: { nestedData: { foo: string; bar: string } } };
    
    type NestedData = Result['data']['nestedData'];
    

    但是,当 data 属性可为Null,这不起作用:

    type Result = { data: { nestedData: { foo: string; bar: string } } | null };
    
    type NestedData = Result['data']['nestedData'];
    

    并导致错误:

    Property 'nestedData' does not exist on type '{ nestedData: { foo: string; bar: string; }; } | null'.(2339)
    

    我如何定义我的 NestedData 键入 Result 结果 是谁的打字机?

    Demo on TypeScript Playground

    编辑:我正在拿我的 嵌套数据 从codegen工具中键入,我正在定义 嵌套数据 作为较短的类型别名。实际上,打字时间更长,所以我想尽量减少重复。

    2 回复  |  直到 5 年前
        1
  •  1
  •   kaya3 Amit Bera    5 年前

    你可以用 Exclude 除去 null

    type NestedData = Exclude<Result['data'], null>['nestedData']
    

    Playground Link

    当你无法改变自己的想法时,这样做是有道理的 Result 出于某种原因键入。在其他情况下,更自然的定义是:

    type NestedData = { foo: string; bar: string }
    type Result = { data: { nestedData: NestedData } | null }
    
        2
  •  1
  •   ruohola    5 年前

    type Result = {
        data: {
            nestedData: { foo: string; bar: string }
        } | null
    };
    
    type GetNullable<T, Prop extends keyof NonNullable<T>> = NonNullable<T>[Prop]
    
    type NestedData = GetNullable<Result['data'], 'nestedData'>
    
    

    Playground

    推荐文章