Exploring the Power of Typescript and Graphql Fragments

Utilizing codegen, I automatically generate TypeScript types and employ Apollo client to submit requests to the server.

However, when I execute code generation for the given example, TypeScript fails to recognize that the people object contains firstName and lastName fields. It only acknowledges the presence of the avatar field. The issue can be resolved by eliminating the fragment and directly including the fields in the query.

How can I ensure proper support for fragments in this scenario?

fragments/person.graphql

fragment NameParts on Person {
  firstName
  lastName
}

queries/person.ts

import { graphql } from '@/gql'

export const getPersonDocument = graphql(`
   query GetPerson {
     people(id: "7") {
       ...NameParts
       avatar(size: LARGE)
     }
   }
`)

'@/gql' denotes the output directory of codegen

Answer №1

To solve the issue, I disabled fragmentMasking

  generates: {
    './src/gql/': {
      preset: 'client',
      presetConfig: {
        fragmentMasking: false,
      },
    },
  },

Answer №2

In order to properly utilize the fragment, make sure to include it in the same file where your query is declared

queries/person.ts:

import { graphql } from '@/gql'
import personFragment from 'fragments/person.graphql'

export const getPersonDocument = graphql(`
   ${personFragment}

   query FetchPersonDetails {
     person(id: "7") {
       ...PersonalInfo
       profilePic(size: LARGE)
     }
   }
`)

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

`express-validator version 4 is not functioning as expected`

Trying to implement input validation using express-validator v4.3.0 for my express routes, but despite following the documentation, I am unable to get it working correctly. It seems to not detect any errors and also gets stuck in the route. Could it be tha ...

Advanced Typescript contains a parameter that specifies the type of callback function

Is it possible to create a function that is more typesafe than the current implementation? public addBusinessRule(targetProperty: string, dependentProperties: string[], callback: (dep0: any, dep1: any, ...)): void { // s ...

What steps can I take to perform unit testing on a custom element?

While working on a project where I have a class that extends HTMLElement, I came across some interesting information in this discussion: https://github.com/Microsoft/TypeScript/issues/574#issuecomment-231683089 I discovered that I was unable to create an ...

Modify the database entry only if the user manually changes it, or temporarily pause specific subscriptions if the value is altered programmatically

After a change in the viewmodel, I want to immediately update the value on the server. class OrderLine { itemCode: KnockoutObservable<string>; itemName: KnockoutObservable<string>; constructor(code: string, name: string) { ...

Creating an HTML tag from Angular using TypeScript

Looking at the Angular TypeScript code below, I am trying to reference the divisions mentioned in the HTML code posted below using document.getElementById. However, the log statement results in null. Could you please advise on the correct way to reference ...

The TypeScript import statement is causing a conflict with the local declaration of 'Snackbar'

I'm having trouble using the Snackbar component from Material UI in my React app that is written in TypeScript. Whenever I try to import the component, I encounter an error message saying: Import declaration conflicts with local declaration of &apos ...

`How to utilize the spread operator in Angular 4 to push an object to a specific length`

One issue I'm facing is trying to push an object onto a specific index position in an array, but it's getting pushed to the end of the array instead. this.tradingPartner = new TradingPartnerModel(); this.tradingPartners = [...this.tradingPartner ...

Adjusting the dimensions of the cropper for optimal image cropping

I am currently working on integrating an image cropper component into my project, using the react-cropper package. However, I am facing a challenge in defining a fixed width and height for the cropper box such as "width:200px; height:300px;" impo ...

Importing 100 .ts files in a dynamic manner

Forgive me for my lack of experience in TypeScript, but I have a query regarding loading multiple .ts files. Imagine I have a directory containing 100 .ts files. Is it appropriate to load all these files using the fs module, as shown below? readdirSync(__ ...

The Apollo Client query returns unexpected null values even though the GraphQL Playground is successfully returning valid

After successfully adding a user to my database, I am encountering an issue where the query returns null in my client app even though it shows data in the GraphQL playground. To troubleshoot this problem, I have implemented a useEffect hook that triggers t ...

Issue in TypeScript where object properties may still be considered undefined even after verifying using Object.values() for undefined values

I'm encountering an issue with TypeScript regarding my interface MentionItem. Both the id and value properties are supposed to be strings, but TypeScript is flagging them as possibly string | undefined. Interestingly, manually checking that id and va ...

The initial rendering of components is not displayed by Vue Storybook

The functionality of the storybook is effective, but initially, it fails to "render" the component. By examining the screenshot, we can deduce that the component-template is being utilized in some way, as otherwise, the basic layout of the component would ...

What is the best way to display suggested words from a given list of options?

Looking for a way to provide suggestions to users based on a list of words they enter in TypeScript while maintaining performance. How can this be achieved efficiently? ...

Angular2: Promise Rejection: Quotes cannot be used for evaluation in this component

I'm currently working on a component in Angular that includes an input parameter: import {Component, Input} from '@angular/core'; @Component({ selector: 'comment', template: ` <div class="col-lg-6 col-md-6 ...

Angular strictPropertyInitialization - best practices for initializing class members?

When initializing a component, I need to retrieve user information. However, with the Angular strict mode in place, I'm uncertain about where to fetch this data. I have considered 3 options. But which one is the most appropriate? Is there another alt ...

Enhancing native JavaScript types in TypeScript 1.8 with the power of global augmentation

Currently, I am working on expanding the capabilities of native JavaScript types using the new global augmentation feature in TypeScript 1.8, as detailed in this resource. However, I'm encountering difficulties when the extension functions return the ...

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Tips for showcasing unique keywords in Ace Editor within the Angular framework

Can anyone help me with highlighting specific keywords in Angular using ace-builds? I've tried but can't seem to get it right. Here's the code snippet from my component: Check out the code on Stackblitz import { AfterViewInit, Component, ...

How to handle form-data in NestJS Guards?

I've been trying to access form-data in my NestJS Guards, but I'm experiencing some difficulties. Despite following the tutorial provided here, I am unable to see the request body for my form-data input within the Guard itself. However, once I ac ...

Experimenting with a Collection of Items - Jest

I need to conduct a test on an array of objects. During the test coverage analysis of the displayed array, I found that the last object with the key link has certain conditions that are not covered. export const relatedServicesList: IRelatedServiceItem[ ...