Tips for specifying a clear type in TypeGraphQL when dealing with key-value pair objects

In my efforts to define explicit types in type-graphql for key-value pairs, I am encountering an issue. I have declared the key-value pair using [key: string]: string, indicating that the keys can be of any string type and the values must be strings. This allows me to create objects like {a: 'a', b: 'b', c: 'c'} where I can add key-value pairs freely. However, I am puzzled about how to specify an explicit type for this key-value pair in type graphql. Below is a snippet of my code:

@ObjectType()
export class Result {
  @Field({ nullable: true })
  domainName?: string;

  @Field(() => [String], { nullable: true })
  uniqueIds?: string[];

  @Field({ nullable: true })
  resultKeyVal: { [key: string]: string };
}

The error I'm facing is: 'Unable to infer GraphQL type from TypeScript reflection system. You need to provide an explicit type for 'resultKeyVal' of the 'Result' class.'

If you look at the second field 'uniqueIds', I was able to provide an explicit type. However, when it comes to the third field 'resultKeyVal', I'm unsure about how to specify the explicit type.

Any guidance on achieving this would be greatly appreciated!

Answer №1

In order to implement a custom GraphQL Scalar, it is necessary.

Luckily, the graphql-scalars library already includes the scalar called GraphQLJSONObject:

  1. To incorporate graphql-scalars:

    npm install --save graphql-scalars
    
  2. Revise the Result class:

    // ...
    import { GraphQLJSONObject } from 'graphql-scalars';
    
    // Various JSON value types
    export type JSONValue =
      | string
      | number
      | boolean
      | null
      | { [key: string]: JSONValue }
      | Array<JSONValue>;
    
    @ObjectType()
    export class Result {
      @Field({ nullable: true })
      domainName?: string;
    
      @Field(() => [String], { nullable: true })
      uniqueIds?: string[];
    
      // Adjust field
      @Field(() => GraphQLJSONObject, { nullable: true })
      resultKeyVal?: { [key: string]: JSONValue };
    }
    

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

Utilizing Angular 16 to Link Component Input with Parent Route Parameter

Picture a scenario where there is a component (some.component.ts) in Angular 16 that retrieves the value for its foo property from activeRoute, specifically from the parent route. Take a look at the code snippet below: @Input() foo!: string; constructor(p ...

Angular 17 isn't notifying child component of signal changes

In the statistics module, I have a signal that specifies the type of charts to display and this signal is updated through a radio button group. The signal: typeSignal = signal<string>('OIA') The radio buttons for setting the : <div clas ...

When working with Visual Studio and a shared TypeScript library, you may encounter the error message TS6059 stating that the file is not under the 'rootDir'. The 'rootDir' is expected to contain all source files

In our current setup with Visual Studio 2017, we are working on two separate web projects that need to share some React components built with TypeScript. In addition, there are common JavaScript and CSS files that need to be shared. To achieve this, we hav ...

Utilizing ngModel within a nested ngFor loop in Angular to capture changing values dynamically

I have been working on developing a screen using Angular and I'm facing an issue with binding values using ngModel. https://i.sstatic.net/DCJ3T.png Here is my implementation. Any help would be appreciated. The model entity I am using for binding the ...

Switching the color scheme while utilizing React Context and MaterialUI

Currently, I'm attempting to implement a toggle feature for switching between dark and light modes using a custom palette in MaterialUI. Unfortunately, I'm encountering Type errors related to the value and theme props for the context provider and ...

Unexpected INTERNAL error encountered with Firebase's Cloud Function update

Currently, I am immersed in a project involving Vue.js 3, Typescript, and Firebase. However, while attempting to integrate new cloud functions, I came across an unexpected issue: Failed to load resource: the server responded with a status of 500 () Un ...

Loop through object properties with *ngFor

Seeking suggestions on how to iterate over object keys in HTML using *ngFor within Angular 12. The provided data structure is as follows: { "data": [ { "student1": { "name": "Jhon", &quo ...

Using Next.js, it is not possible to use absolute imports within SASS

Having trouble utilizing @/ imports within my scss files. The variables I need are stored in src/styles/_variables.scss Here is my tsconfig.json: { "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "baseUrl": ".", "allowJs": tr ...

Passing along the mouse event to the containing canvas element that utilizes chart.js

Recently, I created a custom tooltip for my chart.js chart by implementing a div that moves above the chart. While it works well, I noticed that the tooltip is capturing mouse events rather than propagating them to the parent element (the chart) for updati ...

Is it possible to use Date as a key in a Typescript Map?

Within my application, I have a requirement for mapping objects according to specific dates. Given that typescript provides both the Map and Date objects, I initially assumed this task would be straightforward. let map: Map<Date, MyObject> = new M ...

Ways to invoke a slice reducer from a library rather than a React component

I've been working on a React application using the React Boilerplate CRA Template as my foundation. This boilerplate utilizes Redux with slices, which is great for updating state within a React component. However, I'm facing a challenge when try ...

Error: The function $compile does not exist

Currently, I am working on developing an AngularJS directive using TypeScript. While testing my code in the browser, I encountered the following error: TypeError: $compile is not a function at compileComponent.js:14 Interestingly, the TypeScript compiler ...

Retrieving a specific user attribute from the database using Angular

Currently, I am working on developing an application that utilizes ASP.NET for the Back End (API) and Angular for the Front End of the application. Within the API, I have set up controllers to retrieve either a list of users from the database or a single ...

Modifying preset values in settings.json within the [Extension Development Host] environment

Currently, I am developing an extension in VS Code and I want to implement a feature where a pop-up with a text message input appears when the extension first runs. The user input from the pop-up will be used to modify the default settings in the settings. ...

Simple method for wrestling with objects in TypeScript HTTP POST responses

Can anyone help me understand how to extract information from an object received through an HTTP POST request? Below is the code I am using: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); The issue aris ...

Stripe detects that no signatures match the expected payload

Currently working on setting up a checkout session using Stripe that triggers my webhook upon successful completion. The issue I am facing is an error message stating "error: No signatures found matching the expected signature for payload. Are you passing ...

Tips for resolving the error message "TypeError: Converting circular structure to JSON"

I had a straightforward query where I needed to select all from the aliases table. Everything was working fine until I ran npm update. TypeError: Converting circular structure to JSON public async fetchAliases(req: Request, res: Response): Promise< ...

Issue with subscribing in a MEAN stack application

Currently, I have completed the backend development of my application and am now working on the frontend. My focus at the moment is on implementing the register component within my application. Below is the code snippet for my Register Component where I a ...

Accessing Nested Arrays in Angular 8: Retrieving Data in HTML Template from Multiple Layers of Arrays

Hello there. I'm using an API that gives me the following data: (4) [{…}, {…}, {…}, {…}] 0: dueDate: "2018-03-26T00:00:00" priority: {priorityId: 1, priorityName: "Critical", priorityColor: "red"} statuses: Array(1) 0: ...

Issue with MUI icon import: React, Typescript, and MUI type error - Overload does not match this call

Within my component, I am importing the following: import LogoutIcon from "@mui/icons-material/Logout"; import useLogout from "@/hooks/auth/useLogout"; const { trigger: logoutTrigger } = useLogout(); However, when utilizing this compo ...