Encountering a WriteableDraft error in Redux when using Type Definitions in TypeScript

I'm facing a type Error that's confusing me

This is the state type:

export type Foo = {
    animals: {
        dogs?: Dogs[],
        cats?: Cats[],
        fishs?: Fishs[]
    },
    animalQueue: (Dogs | Cats | Fishs)[]
}

Now, in a reducer I'm attempting this:

...
someFunction: (state, action: PayloadAction<{ index: number, animalKey: keyof Required<Foo>['animals']}>) => {
    const {index, animalKey} = action.payload
    const animal = state.animalQueue[index]
    state.animals[animalKey]!.push(animal)
}
...

This results in an error:

TS2345: Argument of type 'WritableDraft or WritableDraft or WritableDraft' is not assignable to parameter of type 'Dogs & Cats & Fishs. Type 'WritableDraft' is not assignable to type 'Dogs & Cats & Fishs'. Property 'height' is missing in type 'WritableDraft' but required in type 'Cats'.

I believe this is due to this:

(Dogs | Cats | Fishs)[]

What I'm trying to define here is an array that can contain Dogs, Cats, and/or Fishs. Basically, a mix of all three.

Answer №1

An issue has arisen due to the way TypеScript's type checking is interacting with the definitions you have set for your Foo state. This error specifically relates to ensuring that the types match correctly when adding elements to the animals array based on the animalKey.

The error message suggests that TypеScript is expecting certain properties (like 'height' for Cats) that are not present in the WritablеDraft type you are using.

Below is an updated version of your reducer function:

someFunction: (state, action: PayloadAction<{ index: number, animalKey: keyof Required<Foo>['animals'] }>) => {
    const { index, animalKey } = action.payload;
    const animal = state.animalQueue[index];

    if (animalKey === 'dogs') {
        state.animals.dogs!.push(animal as Dogs);
    } else if (animalKey === 'cats') {
        state.animals.cats!.push(animal as Cats);
    } else if (animalKey === 'fishs') {
        state.animals.fishs!.push(animal as Fishs);
    }
}

Answer №2

We require strict type checking

validateAnimal: (state, action: PayloadAction<{ index: number, animalType: keyof Required<Zoo>['animals'] }>) => {
    const { index, animalType } = action.payload;
    const animal = state.animalQueue[index];
    switch (animalType):
        case 'lions':
            if(isLion(animal)) state.animals[animalType]!.push(animal as Lions);
            break;
        case 'tigers':
            if(isTiger(animal)) state.animals[animalType]!.push(animal as Tigers);
            break;
        case 'bears':
            if(isBear(animal)) state.animals[animalType]!.push(animal as Bears);
            break;
}

where isLion(), isTiger() and isBear() are type guards

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 glitchy dotted lines in an HTML Canvas with the help of translate and scale techniques

I'm working on creating a canvas where users can draw symmetrical lines with their mouse. However, when I use the transform and scale attributes in the draw function to achieve this effect, it creates small gaps in the line and makes it look less smoo ...

Enhance User Experience - Automatically highlight the first element in Prime NG Menu when activated

I have been working on transitioning the focus from the PrimeNG menu to the first element in the list when the menu is toggled. Here is what I've come up with: In my template, I added: <p-menu appendTo="body" #menu [popup]="true&quo ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Add the list of information during the looping process (map)

I am currently facing a challenge where I need to update my data during the iteration and send the results to an API call. The API Call expects a request with data structured in the following format: { list: [{ id: "1", name: "Hello" ...

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

Rails: Utilizing AJAX to dynamically populate Bootstrap dropdown menus

In the setup I have, there is a dropdown responsible for displaying notifications. <li class="notifications dropdown"> <a class="dropdown-toggle" id="dLabel" role="button" data-remote="true" data-toggle="dropdown" data-target="#" href="/notifi ...

Encountering issues with the hyperlink tag '<a>' in an HTML document

I've encountered an issue with the code on my HTML page: <body> <div align="center"> <a href="../index.html"> <img border="0" src="banner1.jpg" width="800" height="120" alt="Ecommerce Knowledge Base"> &l ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

What is the best way to reference an i18n entry within .json files?

I am in the process of creating a user interface using SAP UI5 and my goal is to make all text elements internationalized. Below is a snippet of my view in .xml format where I successfully retrieve text in different languages using placeholders enclosed i ...

What is the process for updating selenium-webdriver if it is not globally installed on my system?

After installing selenium-webdriver with the command npm install selenium-webdriver (without the -g option), I found that the usual instruction of running webdriver-manager update did not work since it was installed locally. What is the correct way to upd ...

URL for image preview on Amazon S3

Is there a way to retrieve preview images from my Amazon S3 image storage instead of always fetching the full-sized 5MB images? If necessary, I would then be able to request the normal image. ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

Filtering nested arrays in Angular by cross-referencing with a navigation menu

In the legacy application I'm working on, we have a navigation menu along with a list of user roles. Due to its legacy nature, we have accumulated a significant number of user roles over time. The main goal is to dynamically display the navigation me ...

Is it possible to disregard any spaces within the content of an <option> element?

In my current project, I am facing an issue where a Django server is sending JSON data to a template with Vue.js running on it. The problem arises from the fact that some values in the JSON data have trailing spaces, causing complications. I am looking for ...

The Vue component seems to be missing the definition of $v for Vuelidate

I've been struggling to resolve this issue. The error message I am encountering pertains to a Vue component that is utilizing the Vuelidate library for form validation. Do you have any insights on what might be causing this error? Uncaught TypeError: ...

What could be causing the JSF ajax status success to fail in Chrome?

Whenever I trigger an action in my ManagedBean, I also initiate a JavaScript function via JSF ajax to display a loading popup while the action is being processed. This functionality works flawlessly in Firefox, however, it seems to encounter issues in Chro ...

Tips for updating the selected date format in a Material Table component using React

In the context of using a material table in React, the columns set up are as follows: columns={[ { title: 'Name', field: 'name', type: 'string', }, ...

What is the best configuration to use for successful MapReduce queries in Riak?

While working on a nodejs application with riak / riak-js, I encountered the following issue: Executing this request db.mapreduce .add('logs') .run(); successfully retrieves all 155.000 items stored in the bucket logs along with their IDs ...

Tips on merging HTML node lists from various `getElement`s

Is there a way to combine HTML elements and extract values using array methods? I am struggling to merge them as a nodeList. I tried using get elements and array.unshift to consolidate elements into one variable. var elemsLabel = document.querySelecto ...