【问题标题】:How to extract a Union from an Array如何从数组中提取联合
【发布时间】:2020-07-01 04:25:12
【问题描述】:

我正在使用 graphql-code-generator 从我的 GraphQL 查询中生成 TypeScript 定义,目前正尝试从数组中提取特定的联合。这在 TypeScript 中可行吗?我找到了an example where someone extracted a type from a generic 并尝试使用Extract 函数,但这不起作用并且只返回never

export type Foo = Array<(
    {
      id: string;
      __typename: 'Data1'
    }
    | {
      id: string;
      __typename: 'Data2'
    }
  )>;

type MyQueryData1 = Extract<Foo, { __typename: "Data1"}>
type MyQueryData2 = Extract<Foo, { __typename: "Data2"}>

TypeScript Playground

【问题讨论】:

标签: typescript


【解决方案1】:

这是你想要的结果吗? ts playground

如果是这样,您必须从数组的元素值中提取出联合类型中的类型,

type MyQueryData1 = Extract<Foo[number], { __typename: "Data1"}>
type MyQueryData2 = Extract<Foo[number], { __typename: "Data2"}>

【讨论】:

  • 是的!非常感谢:-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 1970-01-01
  • 2015-07-13
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
相关资源
最近更新 更多