【问题标题】:Type alias from property that might be null with strictNullChecks使用 strictNullChecks 从可能为 null 的属性中键入别名
【发布时间】:2020-07-29 12:09:12
【问题描述】:

我正在使用graphql-codegen/typescript-apollo-angular 生成可以在我们的 Angular 应用程序中使用的打字稿代码。 我们决定启用strictNullChecks,唯一的问题是我们使用以下模式来指定 API 返回的内部节点的类型:

type ListSomethingEdge = ListSomethingQuery["something"]["edges"][0];

在我的情况下,something 生成为 Maybe<Array<...>>,这是正确的。 当我启用strictNullChecks 时,上面的代码不再起作用,因为某些东西也可能是未定义的/空的。

Property 'edges' does not exist on type '({ __typename?: "SomethingConnection" | undefined; } & Pick<SomethingConnection, "totalCount"> & { edges?: Maybe<{ __typename?: "SomethingEdge" | undefined; } & { ...; }>[] | null | undefined; pageInfo: { ...; } & Pick<...>; }) | null | undefined'.ts(2339)

我找不到有关如何从这样的类型别名中删除 null / undefined 类型的文档。也许有不同的方法可以做到这一点。

【问题讨论】:

    标签: angular typescript strictnullchecks graphql-codegen


    【解决方案1】:

    要从类型中删除 null / undefined,您可以使用 NonNullable 实用程序。

    NonNullable&lt;T&gt; 通过从T 中排除nullundefined 构造一个类型

    type ListSomethingEdge = NonNullable<ListSomethingQuery["something"]>["edges"][0];
    

    Playground


    NonNullable 实用程序是使用 conditional types 构建的

    type NonNullable<T> = T extends null | undefined ? never : T
    

    ** 不需要手动定义,typescript 提供,全局可用。

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 1970-01-01
      • 2020-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2019-10-17
      • 2011-08-13
      相关资源
      最近更新 更多