简体   繁体   中英

Typescript error "Property '0' does not exist on type X" when using code generated graphql code

I'm having hard time understanding how to fix this typing error.

I have this code:

<script lang="ts">
  import type { PlayerListQuery } from "queries";

  export let player: PlayerListQuery["playerList"]["edges"][0]["node"];
</script>

with PlayerListQuery :

export type PlayerListQuery = {
  __typename?: "Query";
  playerList: {
    __typename?: "PlayerConnection";
    edges?: Array<{
      __typename?: "PlayerEdge";
      cursor: any;
      node?: {
        __typename?: "Player";
        name?: string | null;
        age?: number | null;
        id: string;
      } | null;
    } | null> | null;
    pageInfo: {
      __typename?: "PageInfo";
      hasNextPage: boolean;
      hasPreviousPage: boolean;
      startCursor?: any | null;
      endCursor?: any | null;
    };
  };
};

the error is:

Property '0' does not exist on type '({ __typename?: "PlayerEdge" | undefined; cursor: any; node?: { __typename?: "Player" | undefined; name?: string | null | undefined; ... more ...; } | null | undefined; } | null)[] | null | undefined'.ts(2339)

which is referring to ["edges"][0]["node"] .

How to fix this?

The properties edges and Array<[index]> can be null or undefined , that's why you cannot access directly to their child properties.

What you can do to get the non-null values is to use the built-in type helper NonNullable . This will remove all the undefined and null types from the union and it will only leave the base types that can be indexed.

// Use in-between types
type ExistingEdges = NonNullable<PlayerListQuery["playerList"][
    'edges'
 ]>
type ExistingEdgeValues = NonNullable<ExistingEdges[0]>

export let player: ExistingEdgeValues['node'];

// Direct
let player2: NonNullable<NonNullable<PlayerListQuery["playerList"]['edges']>[0]>['node'];

TS Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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