What could be causing TypeScript to identify my immer draft as undefined?

I'm completely lost, can someone please help me with this issue:

Currently, I am trying to update a typed configuration.

Within my Provider component:

const [data, setData] = useImmer<typeof INITIAL_CONFIG>(INITIAL_CONFIG)
...
function updateField(field: MyConfigKeys, value: MyConfigValues): void 
  setData(draft => {
    draft[field] = value 
  })
}

Encountering the following error:

(parameter) draft: WritableDraft<Partial<MyConfigType>>
Type 'MyConfigValues' is not assignable to type 'undefined'.
  Type 'string' is not assignable to type 'undefined'.ts(2322)

Can anyone explain what's happening here?

For further reference, you can check out this sandbox with a basic example: https://codesandbox.io/s/exciting-keldysh-kxvckq?file=/src/App.tsx (where the error shows as never instead of undefined)

Answer №1

The issue arises from TS not being able to enforce the value and field matching. A solution is to introduce generality into the function:

function updateField<K extends MyConfigKeys>(field: K, value: MyConfigType[K]): void {
    setData((draft) => {
      draft[field] = value;
    });
  }

With this modification, TypeScript can now ensure that the value corresponds to the specified field.

Interactive Demo

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

mat-autocomplete Show user-friendly names while storing corresponding IDs

I am currently utilizing a Mat-autocomplete feature that allows for loading a list of "users". Within the autocomplete functionality, I aim to exhibit the username while retaining the selected user ID value. Originally, I had: this.allFruits = val.map( ...

Unit testing an Angular service using Jasmine with a JSON object schema in Angular 2/4

Looking for assistance with unit testing a service I have. The service includes a current json array object that is functioning properly when the observable is subscribed to. However, I seem to be encountering issues with my unit test setup. Can anyone pr ...

Identifying the specific type within a union of types using a discriminator

How can I specify the correct typing for the action argument in the function withoutSwitchReducer as shown below? enum ActionTypesEnum { FOO = 'FOO', BAR = 'BAR', } type ActionTypes = { type: ActionTypesEnum.FOO, paylo ...

What is the best way to determine the condition of a data-target attribute?

Is there a more optimal way to write the following code: <li [ngClass]="sidebarVisible ? 'nav-item' : 'nav-item sidebar-false-new-folder'" *ngIf="sidebarVisible"> <a (click)='this.createNewDirectory()' data-tog ...

Following the build in Angular, it only displays the index.html file and a blank screen

According to the information on Angular's official website, running the "ng build" command should generate files in the dist folder ready for hosting. However, after running this command, the index.html file is empty except for the page title. When yo ...

Update the input value with the selected option from the dropdown menu in Angular

How can I dynamically set the value of an input field based on the selection from a dropdown menu in Angular using Reactive Forms? Below is my HTML code: <nb-card> <nb-card-header> Services </nb-card-header> <nb-card-body&g ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

Within Angular, the Subscribe function is invoked after all other methods in the component have been executed. Consequently, this sequence of events often prevents me from effectively utilizing the response data

Struggling with implementing await and async in TypeScript, especially as a beginner. Below is how I attempted to use them: async refreshList(){ await this.service.refreshList().subscribe(res => { console.log(res); this.service.todoListModel=res; ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

The variable 'data' is not a property of the type 'any[]'

I am currently facing an issue with a dummy service I created to fetch dummy data. When calling this service from a component ts file, I encountered the following error. After searching through some similar posts, I still haven't been able to resolve ...

Unable to retrieve dynamically generated object property from an array in AngularJS 2+

Here is an example of an items array: this.itemList = [ { id: 1, name: 'a', address: 'as dasf a' }, { id: 2, name: 'b', address: 'as dasf a' }, { id: 3, name: 'c', address: 'as dasf a' } ]; ...

Troubleshooting the issue of React forms hook not functioning properly with Material UI Select input

How the Textfield below should load: https://i.sstatic.net/29Sz4.png How it actually loads: https://i.sstatic.net/TdPYM.png My Select component, created using Material UI and React form hook, is not loading the default value as expected. The component ...

The issue persists in VSCode where the closing brackets are not being automatically added despite

Recently, I've noticed that my vscode editor is failing to automatically add closing brackets/parenthesis as it should. This issue only started happening recently. I'm curious if anyone else out there has encountered this problem with their globa ...

Challenges encountered when unit testing ngx-translate

0 I am encountering issues with unit testing while using the ngx-translate library. Despite adding a provider for TranslateService, the tests keep asking for more providers, creating an endless loop of dependencies. Specifically, I am trying to unit test ...

Require data prior to initializing the angular constructor without using a resolver

Currently, I have a dialog service in place. In order to create the dialog component, I utilize viewContainerRef along with ComponentFactory. Once the component is created, I proceed to set a default value for a specific property within this component. t ...

Automatically activate the Focus Filterfield in the ng-multiselect-dropdown upon clicking

I've integrated the ng-multiselect-dropdown package into my Angular project using this link: https://www.npmjs.com/package/ng-multiselect-dropdown. Everything is functioning as expected, but I'm looking to automatically focus on the filter input ...

Extracting data from an array using Angular

Currently, I am developing an Angular application that involves handling an array structured like the one below. [ { Code: "123", Details:[ { Id: "1", Name: "Gary" }, { ...

Issue with Angular Reactive form: Checkbox checked property not binding correctly when the page initially loads

Looking to achieve Two-way data binding of Checkbox in Angular Reactive forms. After checking the checkbox, I am updating the 'isdateChkd' variable and storing it in the state. Despite the variable being set to TRUE, the checkbox does not get aut ...

What is the timing for the execution of top-level non-export code in TypeScript?

I am currently puzzled about the execution of code in files. Let's say we have a file1.ts with the following content: export interface myInterface {} export function myFunction() {} export const myConst: {} // ... and more exports // top-level non- ...

Tips on preventing the duplication of component instances in your project

Check out the plunker link to see that the child component "Loader" is being loaded multiple times every time the button is clicked. How can I prevent creating multiple instances of the same component? I want the new instance to replace the existing one wh ...