What is the correct way to define functions within an object using Typescript in this situation?

Currently in the process of converting a JavaScript project to TypeScript, I encountered this error message (utilizing urql):

A function whose declared type is neither 'void' nor 'any' must return a value. ts(2355)
on line:

playerCreate: (result, args, cache): UpdateResolver => {

Curious as to why this is happening?

const updates = {
  Mutation: {
    playerCreate: (result, args, cache): UpdateResolver => {
      const playersQueries = cache
        .inspectFields("Query")
        .filter((x) => x.fieldName === "players");
      playersQueries.forEach(({ fieldName, arguments: variables }) =>
        cache.invalidate("Query", fieldName, variables)
      );
    },

    playerDelete: (result, args, cache, info): UpdateResolver => {
      // utilizing result, args, and cache here
    },
  },
};

It appears that the declaration for Updateresolver looks like this:

export declare type UpdateResolver = (result: Data, args: Variables, cache: Cache, info: ResolveInfo) => void;

UPDATE:

After receiving feedback, it seems that my understanding is incorrect - I am indicating that the function returns an UpdateResolver while the type refers to the function itself, not the return type.

This leads me to enquire:

How should I properly define the types for playerCreate and playerDelete?

Answer №1

Consider updating the code to this:

const updates = {
  Mutation: {
    playerCreate: (result: Data, args: Variables, cache: Cache): void => {
      const playersQueries = cache
        .inspectFields("Query")
        .filter((x) => x.fieldName === "players");
      playersQueries.forEach(({ fieldName, arguments: variables }) =>
        cache.invalidate("Query", fieldName, variables)
      );
    },

    playerDelete: (result: Data, args: Variables, cache: Cache, info: ResolveInfo): void => {
      // using result, args, cache here
    },
  },
};

UPDATE: A way to achieve this is by utilizing the as operator:

const updates = {
  Mutation: {
    playerCreate: (((result, args, cache) => {
      const playersQueries = cache
        .inspectFields("Query")
        .filter((x) => x.fieldName === "players");
      playersQueries.forEach(({ fieldName, arguments: variables }) =>
        cache.invalidate("Query", fieldName, variables)
      );
    }) as UpdateResolver),

    playerDelete: (((result, args, cache, info) => {
      // using result, args, cache here
    }) as UpdateResolver),
  },
};

What does the as operator do in TypeScript?

It instructs the TypeScript compiler to treat the expression before the operator as the type specified after the operator. It allows for some unconventional behavior:

const test = "some string" as number;
// "test" is a number in this instance!!

Exercise caution when employing it! When used with functions, TypeScript expects parameter one to have type T, so it assumes that the function also accepts a parameter of type T.

An alternative to as exists but cannot be utilized in TSX files:

const something = <number>"hello";
// Avoid unless you are certain of the actual type!

The example provided is incorrect as TypeScript will view the string as a number, even though it isn't. However, it demonstrates the concept of type assertion.

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

Leveraging typegoose in a multitenant environment within the nestjs framework

I am looking to implement multitenancy functionality where each tenant will have its own database. Can Typegoose dynamically create connections for this purpose? ...

Tips for creating a custom hook that is type safe:

When I use the custom function createUser, I've noticed that I can pass numbers instead of strings without receiving an error. Surprisingly, even if I forget to include an argument, no red squiggles appear. const [userState, createUser] = useCre ...

Tips for setting up a personalized preview mode in Sanity Studio using Next.js

I am facing an issue displaying the preview mode because the URL must contain specific parameters such as "category" and "slug" (as shown in the image below). Here is the error URL with undefined parameters Therefore, I am unable to retrieve the paramete ...

Next.js React Server Components Problem - "ReactServerComponentsIssue"

Currently grappling with an issue while implementing React Server Components in my Next.js project. The specific error message I'm facing is as follows: Failed to compile ./src\app\components\projects\slider.js ReactServerComponent ...

Tips for creating basic Jasmine and Karma tests for an Angular application to add an object to an array of objects

I have developed a basic Angular project for managing employee data and I'm looking to test the addProduct function. Can someone guide me on how to write a test case for this scenario? I am not using a service, just a simple push operation. Any assist ...

What are some ways to make autorun compatible with runInAction in mobx?

Currently delving into the world of mobx and runInAction, facing a challenge in comprehending why autorun fails to trigger my callback in this particular scenario: class ExampleClass { // constructor() { // this.exampleMethod(); // } ...

An interface that is extended by an optional generic parameter

I currently have an exported abstract class that has one generic. However, I now require two generics. I do not want to modify all existing classes that are using this class. Therefore, I am looking to add an optional generic class that extends an interfac ...

Instructions for disabling editing for a specific cell within an inline editable row in primeNG

I am currently using PrimeNG DataTable with Angular, where the rows are editable as shown in the example in the documentation: https://www.primefaces.org/primeng/#/table/edit. However, I am facing an issue where I want to exclude one cell from being editab ...

Generating swagger documentation for TypeScript-based Express applications

I have successfully set up the swagger URL following a helpful guide on configuring Swagger using Express API with autogenerated OpenAPI documentation through Swagger. Currently, I am utilizing TypeScript which outputs .js files in the dist folder without ...

What is the best way to conduct tests on Typescript modules that are not intended for

Even though the compiler accepts my current solution without any errors, the tests are still failing with the message "ReferenceError: myFunction is not defined". I am interested in testing the functionality of the following module using TypeScript: File1 ...

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 ...

Limit class generic to specify constructor argument type

I have a unique object that I need to transform into various structures based on its keys. Each key-value pair must be treated individually, so I intend to convert the object into an array of entries, then map those entries into policy objects and finally ...

Struggling with setting up the onChange function in a Next.js application

After successfully writing and testing the code here, I encountered an error preventing me from building it. Please review the code for any issues. I am attempting to set onChange to handle user input in a text field. Currently using onChange={onChange}, ...

Obtain both the key and value from an Object using Angular 2 or later

I have a unique Object structure that looks like this: myCustomComponent.ts this.customDetails = this.newParameter.details; //the custom object details are: //{0: "uniqueInfo", // 5: "differentInfo"} The information stored in my ...

Encountering errors while setting up routes with Browser Router

When setting up a BrowserRouter in index.tsx, the following code is used: import './index.css'; import {Route, Router} from '@mui/icons-material'; import {createTheme, ThemeProvider} from '@mui/material'; import App from &ap ...

Testing Angular: Implementing Mock Classes and Services using the Any Data Type

When mocking services without using TestBed and instead relying on Fake Classes, is it considered a best practice to use a Mock with the : any data type? If not, errors like missing items/parameters may occur. Although spyOn can be used as an alternative, ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

Encountering a getStaticProps error while using Typescript with Next.js

I encountered an issue with the following code snippet: export const getStaticProps: GetStaticProps<HomeProps> = async () => { const firstCategory = 0; const { data }: AxiosResponse<MenuItem[]> = await axios.post( ...

What is the process to verify a password?

Hey everyone! I've successfully implemented control forms in my login.component.ts for handling email and password input. Now, I want to add these controls to my register.component.ts as well. Specifically, how can I implement controls for the passwor ...

What is the best way to create a fixed array of unchangeable objects?

I am trying to create a class that requires an array of objects as one of its constructor parameters, with the condition that neither the array nor the objects in it can be modified. My current approach involves using the readonly modifier along with the g ...