来自 属性 的类型别名在 strictNullChecks 下可能为 null

Type alias from property that might be null with strictNullChecks

我正在使用 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 类型的文档。也许有不同的方法可以做到这一点。

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

NonNullable<T> constructs a type by excluding null and undefined from T

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

Playground


NonNullable 实用程序是用 conditional types

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

** 无需手动定义,typescript提供,全球通用