typescript create a type from a schema

Recently, I received an auto-generated GraphQL schema mapping that looks like this:

export const generatedSchema = {
  query: {
    __typename: { __type: 'String!' },
    account_sample: {
      __type: '[account_sample!]!',
      __args: {
        distinct_on: '[account_sample_select_column!]',
        limit: 'Int',
        offset: 'Int',
        order_by: '[account_sample_order_by!]',
        where: 'account_sample_bool_exp',
      },
    },
    ...
  }
}

Now, I am eager to create a properly typed object to manipulate inside my implementation, specifically corresponding to the __args object depicted above.

Would it be feasible in TypeScript? In my main logic, I attempted the following:

import { generatedSchema } from '../generated/graphql';

let parms: typeof generatedSchema.query.account_sample.__args;
parms.limit = 400;

Although Vetur seems to comprehend the type we are using, it presents an error when I try to assign values:

(property) limit: "Int"
Cannot assign to 'limit' because it is a read-only property.  Vetur(2540)

I am hopeful that there is a basic aspect of TypeScript that I might be overlooking.

UPDATE:

Upon examining the auto-generated GraphQL schema more closely, I have identified a more suitable candidate for the actual datatype I intend to utilize externally:

export interface Query {
  __typename: 'Query' | undefined;
  account_sample: (args?: {
    distinct_on?: Maybe<Array<account_sample_select_column>>;
    limit?: Maybe<Scalars['Int']>;
    offset?: Maybe<Scalars['Int']>;
    order_by?: Maybe<Array<account_sample_order_by>>;
    where?: Maybe<account_sample_bool_exp>;
  }) => Array<account_sample>;
  ...
}

Do you have any insights on how to import THAT 'args' object as a usable type in a calling program? The objective is to import something that would provide a usable object in my calling program similar to the manually declared:

    interface SuperArgs {
      distinct_on?: Maybe<Array<account_sample_select_column>>;
      limit?: Maybe<Scalars['Int']>;
      offset?: Maybe<Scalars['Int']>;
      order_by?: Maybe<Array<account_sample_order_by>>;
      where?: Maybe<account_sample_bool_exp>;
    }

Answer №1

Thank you for bringing this to my attention. I have identified that this feature is currently missing, and I have created a new issue to track its progress: https://github.com/gqless/gqless/issues/178

In the meantime, a workaround is available:

type SuperArgs = Parameters<typeof Query.account_sample>[0]

By using the above code snippet, SuperArgs can be utilized as a fully functional type within the program without the need for manual declaration.

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

Navigating in Angular with parameters without modifying the URL address

In a nutshell, my goal is to navigate to a page with parameters without showing them in the URL. I have two components: Component A and B. What I want to do is route to B while still needing some parameters from A. I know I can achieve this by setting a ...

Is it possible for me to create a data type representing "potentially undefined strings"?

Just a heads up: I have enabled --strictNullChecks Here is a function I have: export function ensure<T, F extends T>(maybe: T | undefined, fallback: F): T { if (isDefined<T>(maybe)) { return maybe } if (fallback === undefined) { ...

Assigning different data types with matching keys - "Cannot assign type '...' to type 'never'."

I have a question regarding my application, where I am utilizing values that can either be static or functions returning those values. For TypeScript, I have defined the static values along with their types in the following manner: type Static = { key1: ...

How can Multer library be effectively utilized to manage exceptions in NestJS controllers?

While working on creating a service to upload specific files from a Post multipart/form-data request, I came across an easy way to validate the fields count and name sent using the FileInterceptor decorator from @nestjs/platform-express. However, I'm ...

When attempting to use a context, the type '...' cannot be assigned to type '...'

In my Next.js project, I am utilizing createContext to implement a dark mode button. The original jsx file for this functionality is called ThemeContext.tsx, and I am currently in the process of converting it to TypeScript. "use client"; import ...

TypeScript error: Unable to locate namespace 'ng'

I am attempting to utilize a tsconfig.json file in order to avoid having /// <reference tags at the beginning of multiple files. However, I keep encountering this error: [ts] Cannot find namespace 'ng'. any Here is my configuration within ...

detect the dismissal event in the modal controller from the main component

Within my MainPage, I invoke the create function in the ModalController, which displays the ModalPage. Upon clicking cancel, the dismiss function is called and we are returned to the MainPage. The process functions as expected. @Component({ selector: &a ...

SonarLint is suggesting that the parameter currently in use should either be removed or renamed

According to Sonar lint: Suggestion: Remove the unused function parameter "customParams" or rename it to "_customParams" for clearer intention. However, the parameter "customParams" is actually being used in the method "getNextUrl". What am I doing wron ...

Validating Inputs with an Array of Values in my Angular 2 Application

I have been exploring ways to retrieve data from an array of values instead of a single value when using [(ngModel)] binding in my Angular 2 application. The current setup functions perfectly with a single value, as shown below. The data is pulled from the ...

The while-loop using Regex adds only a single value to my array

Within my variable htmlContent, there lies a string filled with properly formatted HTML code, which includes various img tags. The goal is to extract each value from the src attribute of these images and place them all in an array named srcList. The issu ...

Is it possible to observe a class instance without including it in the constructor?

Currently, I'm in the process of testing my Node TypeScript application with Jest. My goal is to avoid altering my existing class, which looks something like this: export class UserRepository { async createUser(userData: User) { const pris ...

Nested function TypeScript declarations

Currently, I am attempting to define a type for my controller function in (nodejs) similar to the following export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) { res.status(200).json({ success: true}); }) ...

The process of linking a Json response to a table

In my products.components.ts class, I am retrieving Json data into the variable this.Getdata. ngOnInit() { this._service.getProducts(this.baseUrl) .subscribe(data => { this.Getdata=data this.products=data alert(JSON.stringify(this.Getdata)); ...

Defining a structure for an entity in which its attributes distinguish between different data types and an array combination

I strongly believe that the best way to showcase this concept is through a clear example: enum EventType { A, B, C }; type MyEvent = [EventType.A, number] | [EventType.B, string] | [EventType.C, number, string]; const eventsGrouped: Record<Event ...

Unable to load content from Three.js Examples library (Error loading script for "three/examples/jsm/loaders/OBJLoader2")

In my Angular application, I have a simple setup using Three.js. When I try to import the `OBJLoader2` from `three/examples/jsm/loaders/OBJLoader2`, everything works fine except when running it with the `ts_devserver`. The browser console shows an error: G ...

What is the best approach to integrating payment solutions into a React Native application running on version 0

Seeking advice on integrating payment systems in React Native 0.70. Previously utilized react-native-credit-card-input and react-native-credit-card-input-plus with earlier versions, but they are now incompatible. ...

An instructional guide on seamlessly incorporating a TypeScript variable into an HTML element submission method

A problem arises in my Angular 8/Django 3 app as I attempt to incorporate a server-side variable called client_secret into the stripe.confirmCardPayment() method. The error message that keeps popping up is Property 'client_secret' does not exist ...

Oops! The Element Type provided is not valid - it should be a string

I have a desire to transition from using Victory Native to Victory Native XL. However, I am encountering an error message saying Render Error Element type is invalid. import * as React from "react"; import { View } from "react-native"; ...

Converting React to Typescript and refactoring it leads to an issue where the property 'readOnly' is not recognized on the type 'IntrinsicAttributes & InputProps & { children?: ReactNode; }'

I'm currently in the process of refactoring an application using Typescript. Everything is going smoothly except for one particular component. I am utilizing the Input component from the library material-ui. import {Input} from "material-ui"; class ...

Creating Meta tags for Dynamic Routes in a Nuxt 3 Build

I recently encountered an issue when trying to implement dynamic OpenGraph meta tags on a dynamically generated route in Nuxt 3 (and Vue 3). I attempted to set the meta tags dynamically using Javascript, as it was the only dynamic option supported by Nuxt ...