What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend:

export const deleteItemFX = createEffect({
  handler: (id: string) => {
    return fetch(itemUrl + id, {
      method: "DELETE",
    });
  }
})

Now, when trying to utilize this effect in my React component by subscribing to its 'finally' event according to the official documentation:

deleteItemFX.finally.watch(({params, status, result}) => {
    console.log('finally.watch called');
    if (result.ok) {
      result.json().then(() => {
        message.success(t("delete_item.success"));
      })
    }
  });

Encountering a type error during compilation:

Property 'result' does not exist on type '{ status: "done"; params: string; result: Response; } | { status: "fail"; params: string; error: Error; }'.  TS2339

Seeking advice or suggestions on how to access the 'result' of the handler within the 'finally.watch' function.

Answer №1

The issue arises when you attempt to extract the property result while destructuring the argument for watch, without first verifying whether status is equal to "done" or "fail".

Take a look at the error message: it states that the property result does not exist within the type:

{ status: "done"; params: string; result: Response; }
| { status: "fail"; params: string; error: Error; }

This represents a union of two object types; in order to access a property from a union, that property must be present on both sides of the union. In this case, result exists only in the first scenario, not the second one. Therefore, prior to reading it, ensure that the data corresponds to the first scenario by utilizing an if statement to refine the type:

deleteItemFX.finally.watch(response => {
    console.log('finally.watch called');
    if (response.status === "fail") {
        // Handle any errors here. TypeScript recognizes that we are in the
        // second part of the union type, so response.error
        // can be accessed within this block
        return;
    }

    // At this point, TypeScript identifies that we are in the first part of the union,
    // and that the property response.result exists, allowing us to access it
    if (response.result.ok) {
      result.json().then(() => {
        message.success(t("delete_item.success"));
      })
    }
  });

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

TS2786 TypeScript is failing to recognize the UI-Kitten components

Error message on IDE: Error Encountered: 'ApplicationProvider' cannot be used as a JSX component. The instance type 'ApplicationProvider' is not a valid JSX element. The types returned by 'render()' are incompatible betwe ...

The type 'string' does not share any properties with the type 'CSSProperties'

How can I resolve the issue of Type 'string' has no properties in common with type 'CSSProperties'? const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = ...

Executing an AngularJS function using regular JavaScript code

I am currently working with AngularJS and Typescript. I have integrated an external library into my project and now I need to call an AngularJS method from that library, which is written in vanilla JavaScript. I tried following this example, but unfortunat ...

Is the autoIncrement property missing from the IDBObjectStore Interface in Typescript 1.8 lib.d.ts file?

Upon examining the specifications on various pages, it is evident that there is a specified read-only property named "autoIncrement" within the IDBObjectStore: https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore https://developer.mozilla.org/ ...

Fixing TypeError in React App: How to Resolve the "Cannot read property 'prototype' of undefined" Issue

I am completely new to JavaScript and I am struggling to understand the error that keeps popping up. After doing some research, it seems like the error could be due to a poorly written function or something along those lines. Here are the classes involved ...

Unlocking the Power of Typescript and ReactJS: Maximizing Efficiency with Previous State

I'm encountering difficulties implementing the previous state in React 18 with Typescript version 4.8.3. Here is my refreshToken code and I'm receiving the following error: Value of type '(prev: any) => any' has no properties in c ...

Utilizing React-hook-Form to transfer data between two SelectBoxes

This simple logic is causing me some trouble. Despite using react-hook-form, I thought this would be easy. However, after struggling with it for over a week, I'm still facing challenges. I'm incorporating nextUI components into my project. < ...

Incorrect date generated by Moment.js from Unix timestamp

Is there a way to store unixtime as a Moment.moment state? Using moment(timestamp) seems to provide a different date. const [date, setDate] = useState<moment.Moment | null>(null); const timestamp = Math.floor(date.getTime() / 1000); setDate(m ...

Validating Forms in TypeScript

Currently in the process of learning Angular 10, but encountering a challenge I have an HTML document that validates a form group in my component. When I set a value for a textbox from my component, the value is displayed correctly, but my submit button c ...

Using class variance authority variants allows for the acceptance of a "null" value, although it is not recommended

My approach with cva is as follows: const checkboxOptions = cva('border ...', { variants: { size: { sm: 'h-4 w-4', md: 'h-5 w-5', lg: 'h-6 w-6', }, }, defaultVariants: ...

Configuring NextJs routes with multiple parameters

Seeking guidance on structuring files in Nextjs for handling multiple URL parameters. Can anyone offer advice? The given URL structure is: /api/upload?file=${filename}&fileType=${fileType} This is the current file structure: app api upload ...

Vue defineProps allows for the definition of complex types for properties

Within my code, I am exploring the use of complex prop types in certain instances. Below is an example of what I have in mind: enum Country { [...] } interface IPerson { firstname: string; lastname: string; } interface IAddress { street: string; ...

A programming element that is capable of accessing a data member, but mandates the use of a setter method for modifications

I am unsure whether I need a class or an interface, but my goal is to create an object with a member variable that can be easily accessed like a regular variable. For example: interface LineRange { begin: number; end: number; } However, I want th ...

What is the best way to create an instance method in a subclass that can also call a different instance method?

In our programming project, we have a hierarchy of classes where some classes inherit from a base class. Our goal is to create an instance method that is strongly-typed in such a way that it only accepts the name of another instance method as input. We d ...

When the button onClick event is not functioning as expected in NextJS with TypeScript

After creating a login page with a button to sign in and hit an API, I encountered an issue where clicking the button does not trigger any action. I have checked the console log and no errors or responses are showing up. Could there be a mistake in my code ...

Implementing a onClick event to change the color of individual icons in a group using Angular

I have integrated 6 icons into my Angular application. When a user clicks on an icon, I want the color of that specific icon to change from gray to red. Additionally, when another icon is clicked, the previously selected icon should revert back to gray whi ...

Error: The property you are trying to set is undefined and cannot

When I attempt to set a property 'error' that is undefined, I receive a TypeError. The problematic line of code looks like this: this.error = error.code; This issue arises in an Angular Reactive Form while making a call to a web service. Below i ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

What is the best way to filter specific data types when using ngFor in Angular?

As I loop through the array named "fruits," which contains objects of type "FruitService" that I created, I want to display each element. However, when I delete them (I know it's strange, no database involved), they turn into type "undefined" and star ...

Mapping object array values to the same key in Angular is a common task that can

Recently, I encountered an object that looks like this: const product = { name: 'watch', color: ['brown', 'white'] } Here's what I'm aiming for: I want to transform this object into the following format: name: ...