Receiving a Typescript error stating "Property '0' does not exist on type X" when incorporating auto-generated GraphQL code into the project

I'm struggling to comprehend how to rectify this typographical error.

Here's the snippet of code causing me trouble:

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

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

involving 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 message reads as follows:

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)

This pertains to

["edges"][0]["node"]
.

What steps can be taken to correct this issue?

Answer №1

In certain cases, the properties edges and Array<[index]> may be null or undefined, preventing direct access to their child properties.

To retrieve non-null values, you can utilize the built-in type helper NonNullable. This will filter out any instances of undefined and null types, leaving only the base types that can be indexed.

// Using intermediary types
type ExistingEdges = NonNullable<PlayerListQuery["playerList"][
    'edges'
 ]>
type ExistingEdgeValues = NonNullable<ExistingEdges[0]>

export let player: ExistingEdgeValues['node'];

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

TS Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2 - Issue: Parameters provided do not correspond to any signature of call target

I'm encountering the following error message: "error TS2346: Supplied parameters do not match any signature of call target." This occurs when attempting to reject a promise, but I believe the code adheres to the required signatures. Any suggestions on ...

Error code -8 occurred while executing the yarn dev command, unable to identify the issue

I'm facing an issue with my development script that is structured like this: "scripts": { "dev": "./test.sh", }, Upon running the 'yarn dev' command, I encounter the following error message: Internal Error: ...

Issue NG1006: Class has two conflicting decorators applied

I encountered an issue while compiling my project: PS C:\Users\hasna\Downloads\A La Marocaine git - Copie\ALaMarocaineFinal\frontend\src\app> ng serve Compiling @angular/forms : es2015 as esm2015 An unhandled exc ...

What distinguishes the ///<reference path="..."/> from an import statement?

Initially, when I try to import React in my code, the TypeScript compiler displays an error saying 'can not find module react'. However, after adding /// before the import statement, the problem is resolved. Interestingly, I later discovered tha ...

Ways to retrieve a value from outside the Angular subscribe block

Custom Template <div class="row" *ngFor="let otc of this.jsonData;index as j"> <div> <table class="table table-striped table-fixed"> <tr *ngFor="let opc of this.winServiceInfo ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

Comparison between TypeScript's variable scope and JavaScript's variable scope

While researching, I discovered some intriguing discrepancies between the documentation regarding a commonly asked question. The TypeScript docs suggest that variables declared with var will escape the containing function's scope, but according to MS ...

The system encountered a TypeError: Unable to access the 'nativeElement' property as it is undefined

Hello, I am a beginner in Angular 2 and currently working on an image cropping plugin. My goal is to display the image on a canvas element. Below is my HTML code: <div class="row"> <div class="col-sm-6"> <canvas id="layout" width="40 ...

The element is implicitly assigned an 'any' type as the expression of type 'string' is unable to be used as an index within the type '{...}'

Trying to improve my react app with TypeScript, but encountering issues when typing certain variables. Here's the error message I'm facing: TypeScript error in /Users/SignUpFields.tsx(66,9): Element implicitly has an 'any' type becaus ...

What is the process for importing an mp3 file into a TypeScript project?

I'm currently working on a web application using React and TypeScript. My current challenge involves importing an mp3 file for use with the use-sound library, but I keep encountering this error in TypeScript: "Cannot find module '../../as ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

Tips for Modifying the currentUrl identifier in Angular 2

I am trying to change the ID property of my currentUrl object within my component. My goal is for the ID to update and then fetch the corresponding data based on that ID. However, I keep encountering this error message: "Cannot assign to read only propert ...

Ensure that Angular waits for the subscription to be completed before triggering the function to generate an Excel

I've encountered an issue with a function that generates an excel from an API request on my webpage. There's a download button that triggers the downloadCSV() function, which usually works fine except when I click it too quickly while navigating ...

NG0303: Unable to establish a connection with 'ngbTooltip' as it is not recognized as a valid property of 'button'

ERROR: 'NG0303: Can't bind to 'ngbTooltip' since it isn't a known property of 'button'.' Encountering this issue in my Angular 12 project when running local tests, the ngbTooltip error is present in all .spec files. ...

What is the best way to define a model class within my Angular 2 component using TypeScript?

As I delve into Angular 2 and TypeScript, I am keen on adopting best practices. I have decided to move away from a simple JavaScript model ({ }) in favor of creating a TypeScript class. However, it seems that Angular 2 is not very fond of my approach. T ...

Unable to link to 'amount' because it is not a recognized attribute of 'ng-wrapper'

I recently made some changes to my code and now I'm encountering the error message "Can't bind to 'count' since it isn't a known property of 'ng-container'" Instead of having both the notification component and notificat ...

The error thrown by Mongoose, stating "TypeError: Cannot read property 'catch' of undefined," is not caught after the data is saved

After updating to Mongoose version 5.0.15, I encountered an error that says TypeError: Cannot read property 'catch' of undefined when trying to save my object with errors found, even though everything was working fine on Mongoose version 4.13.11. ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...