Correctly inputting the 'in' statement - Avoid using a primitive value on the right side of an 'in' statement

I am currently facing an issue with my React code where I am getting the error message:

The right-hand side of an 'in' expression must not be a primitive.
. I am unsure about how to resolve this problem effectively:


    // The goal is to allow null, strings, objects, arrays, etc as potential responses from an API request
    type APIGatewaySuccessResponse = unknown

    ...
    const [data, setData] = useState<T>(null)
    ...
    const fetchData = async () => {
      onLoading()
      const data = await sendRequest<T>(route, options) 

      // Simply checking if data is an object does not prevent the error....
      if (typeof data === 'object' && 'error' in data) {
        setError(data.error)
        onError(data.error)
      } else {
        setData(data)
        onSuccess(data)
      }
     ...

Provided below is the sendRequest code for better understanding:

// Function to make an API request
export const sendRequest = async <T extends APIGatewaySuccessResponse>(
  route: string,
  options?: FetchOptions
): Promise<T | APIGatewayErrorResponse> => {
  const method = options?.method || FetchMethod.POST
  const body = options?.payload ? JSON.stringify(options.payload) : null

  const response = await fetch(route, {
    method,
    headers: {
     ...
    },
    body
  })

  const responseData = await response.json()

  if (response.ok) {
    return responseData as T
  } else {
    return responseData as APIGatewayErrorResponse
  }
}

Since I am using generics, the in function is causing this error. How can I handle this issue while still utilizing generics?

Answer №1

I'm a bit puzzled by the current situation. After doing some research on this issue, it seems that many people have found success with this particular solution: https://github.com/microsoft/TypeScript/issues/43210#issue-829989052, but I still encounter the error regardless of the TypeScript version I use.

However, I managed to overcome the problem by implementing a type guard:

export const isError = (response: any): response is APIGatewayErrorResponse => {
  return 'error' in response
}

Subsequently, I utilized the following approach:

const data = await sendRequest<T>(route, options)
if (isError(data)) {
  setError(data.error)
  onError(data.error)
} else {
  setData(data)
  onSuccess(data)
}

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

Exploring the world of tabbed dynamic routing in Angular 2 version 4

Today I encountered a routing issue that requires assistance from all of you. Currently, I have a sidebar with dynamic tree view navigations on the left and 4 tabs on the right. By default, tab1 is selected to display data related to the active link. Lin ...

Ways to validate email input with pattern in Angular 2

I need help figuring out how to use the email pattern error for validation using the hasError function in Angular 2. My goal is to apply the invalid class to my input field. Below, you can see the code from registration.component.html: <div class="inpu ...

What causes a folder to disappear after rerunning in nest.js?

When working on my project using nest.js in MacOS Sonoma, I encountered a problem where the image folder src/products/images gets deleted after every project rerun (npm start). The images are saved like this: for (const image of images) { const fileName ...

Encountering the error message "The argument type 'AsyncThunkAction<*>' cannot be assigned to the parameter type 'Action<any>'" while trying to utilize a custom typed useAppDispatch hook

For a live example, you can check out this link. In the process of developing a React application with TypeScript and Redux Toolkit, I have meticulously followed the guidelines outlined in the documentation. As a result, I have successfully implemented ty ...

Is there a way to show text as symbols in Primeng components?

Check out this helpful example that demonstrates what I am attempting to achieve. I have implemented p-menu from primeng. Is there a method to convert text into symbols like &trade to ™ and &#8482 to ®? ...

How to retrieve the HTTPClient value in Angular?

APIservice.ts public fetchData(owner: any) { return this.http.get(`${this.url}/${owner}`, this.httpOptions).pipe( catchError(e => { throw new Error(e); }) ); } public fetchDataById(id: number, byId:string, owner: any) { ...

What distinguishes Angular directives as classes rather than functions?

When using Ng directives within HTML tags (view), they appear to resemble functions that are called upon rather than instances of a class. It almost feels like they could be static methods that can be invoked without an instance of a class. Comin ...

JS The clipboardData in ClipboardEvent is perpetually void

I am trying to retrieve files using CTRL+V from the ClipboardEvent in Angular6, but I am encountering an issue where the clipboardData is always empty regardless of whether I test images or text. This problem persists even when tested on the latest release ...

Type of event triggered by user file upload via INPUT element

I have a piece of code that reads the contents of a locally stored file. Here is what it looks like: onFile(event: any) { console.log(event); const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = (ev: any) => { ...

Update to Material-UI 4.8.1 - Is there a different method for defining the `component` property now?

Note: Please note that there was a bug in version 4.8.x which caused this issue. To resolve it, make sure to upgrade to version 4.9.0 or above. In the initial version 4.8.0, the following code would compile and run smoothly: <DialogContent> {/* us ...

Deciphering intricate Type Script Type declarations

I am seeking clarification on how to utilize the object type for sending headers, aside from HttpHeaders provided in the HTTPClient declaration. While working with Angular HttpClient, I aim to include headers using an Object. However, I am unsure of how t ...

The Electron/React/Typescript module is missing: Error: Unable to locate 'fs' in the /node_modules/electron directory

Within my Electron application, I have a file named App.ts. It contains the following code snippet: import { ipcRenderer } from 'electron'; // remaining code However, during the app development process, I encountered this error message: Error: ...

What is a creative way to design a mat-radio-group without traditional radio buttons?

I am looking to create a component that offers users a list of selections with the ability to make only one choice at a time. The mat-radio-group functionality seems to be the best fit for this, but I prefer not to display the actual radio button next to t ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Angular Typescript Filter failing to connect with service injection

I am having trouble accessing the Constant app within a filter in Angular TypeScript. How can I successfully access a service inside a filter? Module App.Filter { import Shared = Core.Shared; export class MilestoneStatusFilter123 { static $inject = ...

Conditionally typing in TypeScript to check if a string contains a specific value

Looking to create a function that takes a string as input and determines whether it contains '[]' or not. If it does, the function should return a list, otherwise an object. This is what I have so far: function customFunction<T = any>(input ...

What is the best approach to eliminate the 'false' type within a setState function in React?

Hey, I've been working on a project that involves using the useState hook and dealing with state using generics. I encountered an issue where I manipulated a fetched array within a setState function using the filter method, which resulted in returnin ...

Did the IBM MobileFirst client miss the call to handleFailure?

I am currently utilizing the IBM MFP Web SDK along with the provided code snippet to send challenges and manage responses from the IBM MobileFirst server. Everything functions properly when the server is up and running. However, I have encountered an iss ...

Setting multiple values on a form can be accomplished by using the appropriate form fields

When it comes to setting values on fields, I am aware that I can choose between using setValue or patchValue However, I am currently encountering a situation where I need to avoid setting the value on each field individually. Take a look at my f ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...