What is the recommended TypeScript type to be returned from a GraphQL resolver when using ESLint?

Repository Link

https://github.com/inspiraller/apollo-typescript

The code is functioning correctly, however, Eslint typescript is raising complaints.

An eslint error occurs on the following code block:

 Query: {
    players: () => players
  }

Missing return type on function.eslint@typescript-eslint/explicit-module-boundary-types

index.ts

import { ApolloServer } from 'apollo-server';
import typeDefs from './schema';
import resolvers from './resolvers';

const init = () => {
  const server: ApolloServer = new ApolloServer({
    typeDefs,
    resolvers
  });

  server.listen().then((props: { url: string }) => {
    const { url } = props;
    console.log(`Server ready at ${url}`);
  });
};

init();

schema.ts

import { gql } from 'apollo-server';

const typeDefs = gql`
  type Player {
    id: String
    name: String
  }
  type Query {
    players: [Player]!
  }

  input PlayerInput {
    name: String
  }

  type Mutation {
    addPlayer(player: PlayerInput!): Player
  }
`;

export default typeDefs;

resolvers.ts

interface shapePlayer {
  id: string;
  name: string;
}
const players: Array<shapePlayer> = [
  {
    id: 'alpha',
    name: 'terry'
  },
  {
    id: 'beta',
    name: 'pc'
  }
];

interface shapeResolver {
  Query: {
    players: () => Array<shapePlayer> | null | undefined | void;
  };
}

const resolvers: shapeResolver = {
  Query: {
    players: () => players
  }
};
export default resolvers;

I have explored various alternative libraries like TypeGraphQL, which appears to be a promising solution for reducing TypeScript boilerplate. However, it does not address the issue of determining the strict return type of a query or mutation.

If anyone has any recommendations or assistance, please feel free to share. Thank you!

Answer №1

If you're looking for a convenient way to automatically generate TypeScript typings from your schema, consider using graphql-code-generator. It might be a bit late, but hopefully, this information can still benefit others.

To quickly convert your schema to TypeScript, simply paste it here for immediate results.


Easy TypeScript setup:

  1. Installation:

npm i -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-resolvers

This will install the necessary CLI and plugins for TypeScript and TypeScript resolvers.

  1. Create a codegen.yml file in your root directory with the following contents:
overwrite: true
schema: 'http://localhost:3500/graphql'
generates:
  src/utils/codegen/graphql.ts:
    plugins:
      - 'typescript'
      - 'typescript-resolvers'
  1. Execute the command:

graphql-codegen --config codegen.yml --watch src/**/*.ts

  1. Utilize the generated types in your code:
// Import the types from your generated TypeScript files.
import { MutationResolvers, QueryResolvers, Resolvers } from '@/utils/codegen/graphql'

const Query: QueryResolvers = {
  players: () => players
}

const Mutation: MutationResolvers = {
  updatePlayer: () => player
}

const resolvers: Resolvers = {
  Query,
  Mutation
};
export default resolvers;

View screenshots for examples:

Intellisense and autocomplete

Proper validation

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

Creating a Loading Sign with a Button Component in React

Request Description: In my form, I have a button that triggers a submission to the backend. While the request is processing, I want the button to display a loading indicator instead of the usual text. Once the request is complete, I need the form to disap ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

Angular HttpClient Catch Return Value

In my quest to develop a universal service for retrieving settings from the server, I've encountered an issue. When errors arise, I want to intercept them and provide a default value (I have a predetermined configuration that should be utilized when e ...

Creating a completely dynamic button in Angular 6: A step-by-step guide

I have been working on creating dynamic components for my application, allowing them to be reusable in different parts of the program. At this point, I have successfully developed text inputs that can be dynamically added and customized using the component ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

Imitate dependencies using Mocha and Typescript

In my typescript project, I am using mocha. Let's consider two modules: // http.ts export class Http { } // app.ts import Http from './http'; export class App { } I want to know how to mock the Http module while testing the App. The te ...

Angular functions fail to update the loop variable

Using the documentSnapshot function in Firestore to verify the existence of a document. The function is executed in a loop up to a value of 5. However, even though the function runs 5 times, the value of 'i' always reflects the last value. The ...

Methods for organizing consecutive elements within an array in Javascript/Typescript

Let's explore this collection of objects: [ { key1: "AAA", key2: "BBB" }, { key1: "BBB", key2: "CCC" }, { key1: "CCC", key2: "DD ...

Create a definition file containing a class that can be easily extended

I am attempting to define an interface in a declaration file: declare namespace Foo{ export interface Bar{ new(attrs, options) } } Then I want to inherit from this interface in my code: class Chunk extends Foo.Bar {} However, I encounte ...

How come the inference mechanism selects the type from the last function in the intersection of functions?

type T = (() => 1) & (() => 2) extends () => infer R ? R : unknown What is the reason that T is not never (1 & 2)? Does the type always come from the last function, or can it come from one of them? ...

Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService. The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status. On the ot ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

Angular - Implementing *ngIf based on URL parameters

Is it possible to display an element based on specific queryParams included in the URL? For example: ngOnInit() { this.route.queryParams.subscribe(params => { console.log(params); }); } If I want to achieve something similar to this: ...

Can a type be created that resolves to either of two specific types?

If I have multiple functions that return either a number or a date, is there a way to define a type that encompasses both? For example, instead of: foo1(): number | Date {} foo2(): number | Date {} Can we do something like this: foo1(): NumberOrDate {} f ...

Converting a string into a Date in Typescript while disregarding the timezone

Upon receiving a date in string format like this (e.g.): "11/10/2015 10:00:00" It's important to note that this is in UTC time. However, when creating a Date object from this string, it defaults to local time: let time = "11/10/2015 10:00:00"; let ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...

Tips for executing Firebase transactions involving read operations subsequent to write operations

Is there a method to incorporate read operations following write operations in nodejs for cloud and background functions? According to the information provided in the documentation, only server client libraries allow transactions with read operations afte ...

Enhance your TypeScript skills by leveraging types on the call() method in redux-saga

Is there a way to specify the types of a function using call()? Consider this function: export function apiFetch<T>(url: string): Promise<T> { return fetch(url).then(response => { if (!response.ok) throw new Error(r ...

Executing methods sequentially in the ngOnInit lifecycle hook consecutively

Working with Angular15 has presented me with a challenge. In my app.component.ts file, I have two methods: “ngOnInit()”, as shown below. public ngOnInit(): void { this.getToken(); this.UserLoggedIn(); } I am looking to run the above two functions in ...