Enhance your coding experience with Angular Apollo Codegen providing intelligent suggestions for anonymous objects

Currently, I am exploring the integration of GraphQL with Angular. So far, I have been able to scaffold the schema successfully using the @graphql-codegen package. The services generated are functional in querying the database.

However, I've noticed that the query results are structured unexpectedly, at least from my perspective. Although everything is strongly-typed, it seems like the intellisense is providing me with strongly-typed anonymous objects (similar to those in C#).

Let's take a look at this particular GraphQL Query:

query Animals {
  animals {
    id
    name
    latinName
    created
    changed
    changedBy
  }
}

When executed against the database, the result returned is in JSON format as follows:

{
    "data": {
        "animals": [
            {
                "id": 1,
                "name": "Rehwild",
                "latinName": "Capreolus capreolus",
                "created": "2023-04-01T19:29:45.513Z",
                "changed": "2023-04-01T19:29:45.513Z",
                "changedBy": ""
            },
            {
                "id": 2,
                "name": "Dammwild",
                "latinName": "Dama dama",
                "created": "2023-04-01T19:29:45.513Z",
                "changed": "2023-04-01T19:29:45.513Z",
                "changedBy": ""
            }
        ]
    }
}

With the code generation process, my expectation was to receive an array of type Animal[] directly under the data property of the response, something akin to the following interface:

export interface Animal {
    id: number;
    name: string;
    latinName: string;
    created: string;
    changed: string;
    changedBy: string;
}

However, in the TypeScript code generated, there exists a type declaration for Animal which includes additional properties not explicitly requested in the above GraphQL query:

/** A specific animal that can be searched for and saved. */
export type Animal = {
  __typename?: 'Animal';
  changed: Scalars['DateTime'];
  changedBy: Scalars['String'];
  created: Scalars['DateTime'];
  id: Scalars['Int'];
  latinName?: Maybe<Scalars['String']>;
  name: Scalars['String'];
  timesDied: Array<Death>;
  timesRescued: Array<Rescue>;
};

Consequently, when attempting to load the data in the constructor of my component:

constructor(private animals: AnimalsGQL) {
    this.animals$ = this.animals.watch().valueChanges.pipe(map(result => result.data.animals));
}

I'm observing a return type different from what I expected, instead of receiving Animal[].

This discrepancy in type description poses challenges in various parts of my code. I would ideally prefer direct referencing to the relevant type rather than referring to an anonymous type. Does anyone know why this behavior is occurring? Details of my setup and the codegen configuration are provided below.

Any assistance on this matter would be highly appreciated.

package.json:

{
  "name": "tests",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "codegen": "cross-env NODE_TLS_REJECT_UNAUTHORIZED=0 graphql-codegen --config codegen.ts"
  },
  "private": true,
  ...
}

codegen.ts


import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  overwrite: true,
  schema: "https://localhost:7029/graphql",
  documents: "src/**/*.graphql",
  generates: {
    "src/graphql/generated/graphql.ts": {
      plugins: ['typescript', 'typescript-operations', 'typescript-apollo-angular'],
      config: {
        addExplicitOverride: true
      }
    },
    "./graphql.schema.json": {
      plugins: ["introspection"]
    }
  }
};

export default config;

Answer №1

Anonymous types do not exist in TypeScript. Frequently, interfaces are mentioned by name in tooltips, while types can be displayed directly in tooltips, but this is not always the case. At times, TypeScript handles it differently.

Ultimately, the content of a tooltip does not impact how TypeScript functions. Whether the type is inlined or referenced by name, TypeScript will treat it identically and it will not affect anything else.

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 - The path to the 'fs' module cannot be resolved in ./node_modules/busboy/lib/main.js

After adding a new React component to my NextJS app, I encountered a mysterious error in my local development environment: wait - compiling... error - ./node_modules/busboy/lib/main.js:1:0 Module not found: Can't resolve 'fs' null Interest ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

The Cypress tests run successfully on a local machine, but encounter issues when running on Gitlab CI

My current setup involves utilizing Cypress to test my Angular application. Interestingly, everything runs smoothly when I execute the tests locally. However, the scenario changes once I run the tests in Gitlab CI as it ends up failing. Looking at my pack ...

Error in Protractor Typescript: The 'By' type does not share any properties with the 'Locator' type

https://i.stack.imgur.com/8j2PR.png All the different versions Error. Protractor version : 5.2.0 npm : 3.10.10 node :6.9.5 typescript :2.6.0 The 'By' type does not share any properties with the 'Locator' type What is the solution to ...

Craft a unique typings file tailored to your needs

After recently creating my first published npm package named "Foo", I encountered some difficulties while trying to consume it in a TypeScript project. The tutorials on how to declare modules with custom typings were not clear enough for me. Here are the k ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

Is there a way to identify the accurate or incorrect array element and modify the component color accordingly?

Upon reviewing the question alternatives, I encountered a problem where clicking on one of the buttons correctly indicated whether it was the correct or incorrect answer by changing its color. However, the issue is that all buttons are being affected by th ...

Tips for incorporating confidence intervals into a line graph using (React) ApexCharts

How can I utilize React-ApexCharts to produce a mean line with a shaded region to visually represent the uncertainty of an estimate, such as quantiles or confidence intervals? I am looking to achieve a result similar to: ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

Implementing express-openid-connect in a TypeScript project

Trying to incorporate the express-openid-connect library for authentication backend setup with a "simple configuration," an issue arises when attempting to access the oidc object from express.Request: app.get("/", (req: express.Request, res: express.Respon ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

Angular 4 file upload verification: Ensuring safe and secure uploads

Is there a recommended method to validate the file type when uploading a file in an Angular 4 form? Are there any simple ways to accomplish this task? ...

I am facing an issue with Nestjs where it is unable to resolve my dependency, despite the fact that it is readily available within the

Encountering the following error: Error: Nest is unable to resolve dependencies of the CreateGroupTask (TaskQueueService, GroupsService, ?, GroupNotificationsService, GroupRepository, Logger). Please ensure that the argument dependency at index [2] is avai ...

"Unexpected Alignment Issue with NZ Zorro's Dynamic Columns Feature in the Ant Design NZ-Table Component

I am facing an issue with a table that receives columns dynamically from the server. The headers and data columns are not aligned properly. How can I ensure that they align correctly? <nz-table *ngIf="queryResults" #headerTable [nzData]="queryResults" ...

Retain the previous selection in Ng-select when clearing the current value

I am attempting to retrieve the value of an ng-select field prior to it being cleared. It appears that all change events only provide the new value at this time. <ng-select [items]="importerFields" [(ngModel)]="selectedConstant[constant. ...

Angular/TypeScript restricts object literals to declaring properties that are known and defined

I received an error message: Type '{ quantity: number; }' is not assignable to type 'Partial<EditOrderConfirmModalComponent>'. Object literal may only specify known properties, and 'quantity' does not exist in type &ap ...

Having trouble setting the default value of a select element with 'selected' in Angular's bootstrap?

Click here I've been facing some difficulties in making the 'selected' tag work to pre-select my default select value. It seems like it might be related to the unique pipe I'm using and how Angular handles it. I have experimented with ...

Utilizing Angular and ASP .Net Web Api in conjunction with Plesk hosting platform

I have successfully created a website using Angular and .NET Framework 5.0. I was able to publish the Angular portion on Plesk and it is working correctly, but I am facing challenges in publishing the .NET Framework app and connecting it with Angular. ...