将类型分配给Maybe类型的嵌套类型的属性

问题描述 投票:1回答:1

我正在尝试将graphql-codegen工具生成的类型分配给属性。我尝试分配的类型是嵌套类型。给定以下类型:

type SomeType = {
  someKey: Maybe<
    { __typename?: "OtherType" | undefined } & 
    { someNestedKey: ({ __typename?: "AnotherType" | undefined } & Pick<AnotherType, "prop1" | "prop2">)[] } 
  >
}

我需要能够:

myProperty: SomeType['someKey']['someNestedKey'] = []

但是,我遇到的问题是someKey的类型是Maybe类型,因此Typescript抱怨someNestedKey类型上没有<Maybe { __typename?: "OtherType" | ...} & { someNestedKey: (...)[] }>属性(即, someKey)。

在打字稿中,您可以使用!方法声明您确实知道与undefined和/或null联合的类型的属性值确实存在于此案件。分配类型时,有没有办法做类似的事情?

因为我正在使用graphql-codegen工具,所以我无法控制这些类型。

typescript graphql typescript2.0 graphql-codegen
1个回答
0
投票

我刚刚在文档中找到了答案。我需要使用NonNullable类型。

myProperty: NonNullable<SomeType['someKey']>['someNestedKey'] = []

参考:https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullablet

© www.soinside.com 2019 - 2024. All rights reserved.