【问题标题】:How to access nested conditional type in typescript如何在打字稿中访问嵌套条件类型
【发布时间】:2023-03-31 09:48:01
【问题描述】:

以下自动生成类型的起源是 GraphQL 查询:

export type OfferQuery = { __typename?: 'Query' } & {
  offer: Types.Maybe<
    { __typename?: 'Offer' } & Pick<Types.Offer, 'id' | 'name'> & {
        payouts: Array<
          { __typename?: 'Payout' } & Pick<
            Types.Payout,
            'weGet' | 'theyGet'
          > & {
              offer: { __typename?: 'Offer' } & Pick<Types.Offer, 'id'>;
              publisher: Types.Maybe<
                { __typename?: 'Publisher' } & Pick<Types.Publisher, 'id'>
              >;
              eventType: Types.Maybe<
                { __typename?: 'EventType' } & Pick<
                  Types.EventType,
                  'id' | 'name'
                >
              >;
            }
        >;
      }
  >;
};

现在我想在我的反应组件中重用部分 OfferQuery 类型,即支付元素。

type Payout = OfferQuery['offer']['payouts'][number];

然而这给了我一个错误"Property 'payouts' does not exist on type 'Maybe{ __typename?: "Offer" | undefined; }..."

您对如何规避此问题并访问付款定义有任何建议吗?

tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "module": "esnext",
    "moduleResolution": "node",
    "noEmit": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strict": true,
    "target": "esnext"
  }
}

Typescript 4.1.3

【问题讨论】:

  • 类型从何而来?我无法重现。我愿意从 fp-ts 下注
  • 我没看懂问题,但我没有使用fp-ts。
  • 请分享可重现的例子

标签: typescript typescript-typings react-typescript


【解决方案1】:

显然唯一的解决方案是在访问数组元素类型之前排除 null 和 undefined:

type Payout = Exclude<OfferQuery['offer']['payouts'], null | undefined>[number];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 2019-05-03
    • 2020-12-17
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多