简体   繁体   English

如何访问 typescript 中的嵌套条件类型

[英]How to access nested conditional type in typescript

The origin of the following autogenerated type is a GraphQL query:以下自动生成类型的来源是 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'
                >
              >;
            }
        >;
      }
  >;
};

Now I would like to reuse parts of the OfferQuery type in my react component, namely a payout element.现在我想在我的反应组件中重用部分 OfferQuery 类型,即支付元素。

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

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

Do you have any suggestions on how to circumvent this issue and access payouts definition anyway?您对如何规避此问题并访问支付定义有任何建议吗?

tsconfig.json 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

Apparently the only solution is to exclude null and undefined before accessing the array element type:显然,唯一的解决方案是在访问数组元素类型之前排除 null 和 undefined :

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM