Perhaps Typescript Maybe is causing an error due to not handling null values properly

I'm puzzled by this error message mentioning null. Doesn't seo?.breadcrumbs || [] already handle the case where breadcrumbs is null?

When I use as SEOPostTypeBreadcrumbs[] in Intro Props, it resolves the issue, but it feels like a temporary fix.

EDIT: It seems to be pointing out that items in the array of breadcrumbs may sometimes be null? This was auto-generated by Wordpress GraphQL tool graphql-codegen

TS2322: Type 'Maybe<{ __typename?: "SEOPostTypeBreadcrumbs" | undefined; } 
& Pick<SeoPostTypeBreadcrumbs, "text" | "url">>[]' is not assignable to type 'SeoPostTypeBreadcrumbs[]'.   
Type 'Maybe<{ __typename?: "SEOPostTypeBreadcrumbs" | undefined; } & Pick<SeoPostTypeBreadcrumbs, "text" | "url">>' 
is not assignable to type 'SeoPostTypeBreadcrumbs'.     
Type 'null' is not assignable to type 'SeoPostTypeBreadcrumbs'.  
intro.tsx(28, 5): The expected type comes from property 'breadcrumbs' which is declared here on type 'IntrinsicAttributes & IntroProps'

seo type:

export type CptNeighborhoodFragment = { __typename: 'CptNeighborhood' } & {
    seo?: Maybe<
        { __typename?: 'PostTypeSEO' } & Pick<
            PostTypeSeo,
            | 'metaDesc'
            | 'metaKeywords'
            | 'metaRobotsNofollow'
            | 'metaRobotsNoindex'
            | 'opengraphAuthor'
            | 'opengraphDescription'
            | 'title'
        > & {
                breadcrumbs?: Maybe<
                    Array<
                        Maybe<
                            { __typename?: 'SEOPostTypeBreadcrumbs' } & Pick<
                                SeoPostTypeBreadcrumbs,
                                'text' | 'url'
                            >
                        >
                    >
                >;
            }
    >;
};

Usage:

<Intro
    title={seo?.title || ''}
    breadcrumbs={seo?.breadcrumbs || []}
/>

Intro Props

interface IntroProps {
    title: string;
    breadcrumbs?: SeoPostTypeBreadcrumbs[];
}

SeoPostTypeBreadcrumbs

export type SeoPostTypeBreadcrumbs = {
    __typename?: 'SEOPostTypeBreadcrumbs';
    text?: Maybe<Scalars['String']>;
    url?: Maybe<Scalars['String']>;
};

Answer №1

To eliminate the presence of nested Maybe wrappers in your code output, consider setting an avoidOptionals object within your codegen configuration.

You also have the option to adjust the definition of the Maybe type from its default T | null to your preferred variation; for example, T | null | undefined.

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

Issue in Angular: Attempting to access properties of undefined (specifically 'CustomHeaderComponent')

I have encountered a persistent error message while working on a new component for my project. Despite double-checking the injection code and ensuring that the module and component export logic are correct, I am unable to pinpoint the issue. custom-header ...

Utilizing the ICollection interface within Angular 6

Just starting out with Angular and I could really use some guidance on how to implement an Angular Reactive Form that will generate the JSON result shown below: { "firstName":"", "middleName":"", "lastName":"", "addressBook":[{ "addressLin ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

Unable to inject NgControl into validator directive in Angular 6

I've encountered a challenge while trying to create a custom validator for a template-driven form. I'm aiming to constructor inject the NgControl of the host element, which is equipped with an NgModel directive. Unfortunately, I'm consistent ...

The return type of a getter is `any` if the object contains a method and is processed by a generic function

I am facing an issue with my code where the getter's return type is set to any, even though the actual return type should be clear. There are certain additional functions triggering this behavior: // This is necessary for reproduction const wrapperFun ...

Using `await` or `then` with a Promise object can lead to varying results

Here is an example of code that compiles successfully import yargs from "yargs"; const parser = yargs(process.argv.slice(2)). usage("$0 [filename]"). demandCommand(1); async function main() { const argv = await parser.argv ...

Angular 4: Unidirectional data flow from View to Component

Struggling to secure user credentials in my Angular form due to 2-way data binding displaying encrypted values within the component. Here's the code snippet: <form> <div class="input-group"> <span class="input-group-a ...

Encountering a "Module parse failed" error with type annotations in Nextjs while using Yarn Workspaces

I decided to experiment with transitioning a project from using Vite and React to Next.js and React. After reviewing the documentation on this page: https://nextjs.org/learn-pages-router/foundations/from-react-to-nextjs/getting-started-with-nextjs I made t ...

Utilizing React MUI Autocomplete to Save Selected Items

Exploring the realms of React and TypeScript, I find myself puzzled by a task at hand. It involves storing user-selected options from an Autocomplete component and subsequently sending these values to an external API. Is there a recommended approach for ac ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Exploring the Power of Angular 5 with TypeScript and ES2015 Syntax

I have been working on an angular 5 application where I needed to incorporate the dmn-js library. Unfortunately, this library does not come with typings available. To tackle this issue, I followed the guidelines provided in the Angular-CLI wiki regarding h ...

Every time I click a button that triggers this.updateFn(...), I constantly encounter the error message indicating that this.updateFn(...) is not a function

In my current Angular project, I am attempting to call the following function: updateFn: () => (val: boolean) => void; I have tried invoking it like so: this.updateFn()(true); However, I consistently receive a this.updateFn(...) is not a function ...

Replace deprecated TypedUseSelectorHook with createSelectorHook for improved functionality

In my TypeScript code, I used the following to create a typed selector with Redux: import { useSelector, TypedUseSelectorHook } from 'react-redux'; export interface RootState { user: { account: string; } }; export const useTyped ...

Is there a way to modify the id parameter in the URL using Angular 2's ActivatedRoute?

How can I modify a parameter in the URL without altering the overall address? https://i.stack.imgur.com/LOd4T.png This is the TypeScript code that I currently have: onRowClicked(event: any) { let currentIdPerson = event.data.IdPerson; } I am trying ...

Pausing repetitive HTTP requests in an Angular 6 project within a do while loop

While waiting for the completion of one API call, I am recursively consuming an external API. The http calls are being made using import {HttpClient} from '@angular/common/http' As a newcomer to the framework, there may be something wrong in the ...

Can Vue props accept a generic type argument?

Currently, I have a basic component that is receiving the following props: props: { options: { type: Array as PropType<unknown[]>, default: () => [] }, labelKey: { type: String, default: "label" ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

Executing the command `subprocess.run("npx prettier --write test.ts", shell=True)` fails to work, however, the same command runs successfully when entered directly into the terminal

Here is the structure of my files: test.py test.ts I am currently trying to format the TypeScript file using a Python script, specifically running it in Command Prompt on Windows. When I execute my python script with subprocess.run("npx prettier --w ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

The initial Get request does not receive data upon first attempt

In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once ...