Utilize React's useState hook in combination with TypeScript to effectively set a typed nested object

In my project, I have a burger menu component that will receive two props: 1) isOpen, and 2) a file object

{ name, type, size, modifiedAt, downloadUrl }

I'm attempting to implement the following code snippet, but I am encountering issues with Typescript

const FileManagerSlide = () => {
  const [burger, setBurger] = useState({
    isOpen: false,
    file: {
      name: null,
      modifiedAt: null,
      size: null,
      type: null,
      downloadUrl: null
    }
  });


  ...

                  <Tr
                  onClick={() =>
                    setBurger({
                      isOpen: true,
                      file: {
                        name: "HR STUFF",
                        modifiedAt: "01/03/2019",
                        size: 40,
                        type: "folder",
                        downloadUrl: "www.google.com"
                      }
                    })
                  }
                >

The error message I'm receiving is as follows:

ERROR in [at-loader] ./src/components/file-manager/file-manager-slide.tsx:287:31
    TS2345: Argument of type '{ isOpen: true; file: { name: string; modifiedAt: string; size: number; type: string; downloadUrl...' is not assignable to parameter of type 'SetStateAction<{ isOpen: boolean; file: { name: null; modifiedAt: null; size: null; type: null; d...'.
  Type '{ isOpen: true; file: { name: string; modifiedAt: string; size: number; type: string; downloadUrl...' is not assignable to type '(prevState: { isOpen: boolean; file: { name: null; modifiedAt: null; size: null; type: null; down...'.
    Type '{ isOpen: true; file: { name: string; modifiedAt: string; size: number; type: string; downloadUrl...' provides no match for the signature '(prevState: { isOpen: boolean; file: { name: null; modifiedAt: null; size: null; type: null; downloadUrl: null; }; }): { isOpen: boolean; file: { name: null; modifiedAt: null; size: null; type: null; downloadUrl: null; }; }'.

I am considering defining a File type and casting the file attribute of the burger state as that type. Do you think that would resolve the issue?

interface File {
  name: string;
  modifiedAt: string;
  size: number;
  type: string;
  downloadUrl: string;
}

However, I am unsure about how to go about doing that

Answer №1

If you're looking to implement this logic in your code, consider the following approach:

Start by defining a type for the "file" property within your component's state.

type TFile={
   name?:string,
   modifiedAt?:string,
   size?:number,
   type?:string,
   downloadUrl?:string
 }

All properties within the type are marked as optional.

Next, specify the type for the "file" property in your component function:

const [burger,setBurger]=React.useState({
    isOpen:false,
    file:{} as TFile
  })

In order to avoid TypeScript complaints regarding undefined values, set the file property to an empty object since all properties are optional. If you prefer other properties to be treated as "null," adjustments to the TFile type would be necessary.

An alternative syntax option is:

 file:<TFile>{}

However, when working with a tsx file, only the "as TFile" syntax can be used.

Following these steps, TypeScript should not raise any issues when setting the state within your click handler:

setBurger({isOpen:false, file: {
                    name: "HR STUFF",
                    modifiedAt: "01/03/2019",
                    size: 40,
                    type: "folder",
                    downloadUrl: "www.google.com"
                  }}) -->>should be ok 

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

Conflicting Angular controller names within different modules

I'm facing an issue where two modules (A and B) with controllers of the same name are conflicting when imported into module C. Is there a recommended solution to prevent this conflict, such as using a naming convention like "module.controller" for ea ...

Tips for executing a function when nearing the bottom of a scroll:

I have incorporated the angular2-infinite-scroll plugin, specifically version 0.1.4. You can view my plunker here. Currently, the function onScrollDown() only runs once at the beginning when scrolling. I attempted to adjust the values for infiniteScroll ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

Tips for updating the icon based on the active or inactive status in ag-grid within an angular application

HTML* <ng-template #actionButtons let-data="data"> <div class="cell-actions"> <a href="javascript:;" (click)="assign()"> <i nz-icon nzType="user-add" nzTheme= ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...

What are the potential drawbacks of using this alternative method instead of `useCallback` in React to prevent unnecessary re-renders of children components?

While exploring some code, I stumbled upon an alternative method to prevent function recreation during renders compared to the official useCallback hook. This method seems to offer certain benefits over useCallback, but I am interested to know if there are ...

I encountered an issue with Typescript Jest where it was unable to find the mock or mockReturnedValue functions on the types I

Let's test out this interesting class: //RequestHandler.js import axios, {AxiosInstance} from 'axios'; import settings from './settings'; const axiosHandler: AxiosInstance = axios.create({ baseURL: 'http://localhost:8081&a ...

The specified resource cannot be found in the CDK Stack Export

I'm facing an issue while trying to import values generated and exported from a cdk stack that deploys into eu-west-1 into a different stack that needs to be deployed into af-south-1. The error message states that the export name does not exist: EU n ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Error Type: Jest: A transform is required to have a `process` function in order for it to

Encountering an error while running 'npm test': FAIL __tests__/unit/domain/services/demo-service.ts ● Test suite failed to run TypeError: Jest: a transform must export a `process` function. at ScriptTransformer._getTransformer ( ...

Using Vue-router and Typescript with beforeEnter guard - utilizing validated data techniques

As I utilize Vue along with vue-router and typescript, a common scenario arises where a single page is dedicated to displaying a Photo component. A route includes a beforeEnter guard that checks my store to verify the existence of the requested photo. ...

The generic type does not narrow correctly when using extends union

I'm working with the isResult function below: export function isResult< R extends CustomResult<string, Record<string, any>[]>, K extends R[typeof _type] >(result: R, type: K): result is Extract<R, { [_type]: K }> { ...

When choosing the child option, it starts acting abnormally if the parent option is already selected in Angular

I am encountering an issue while trying to select the parent and its children in the select option. The concept is to have one select option for the parent and another for the child. I have parent objects and nested objects as children, which are subCatego ...

Steps for incorporating a filter feature in an Angular Material table

.HTML: Can someone assist me with implementing a filter in this component? I tried using it with the expansion table, but unfortunately, the filter is not working as expected. <mat-dialog-content style="width: 63rem; overflow: initial;"&g ...

Learn the process of sending a delete request to a REST API with Angular

Is there a way to effectively send a delete request to a REST API using Angular? I am attempting to send a delete request with an ID of 1 My current approach is as follows: this.http.delete(environment.apiUrl+"id="+1).subscribe(data => { }); The va ...

Creating a JSON utility type for an already existing type, such as JSON<SomeExistingType>

Is there any tool or utility available that can accomplish this task? const foo: Foo = { ... } const bar: string = JSON.stringify(foo) const baz: JSON<Foo> = JSON.parse(foo) JSON<Foo> would essentially mirror all the properties of Foo, with th ...

Tips for successfully mocking axios.get in Jest and passing AxiosPromise type value

I attempted to simulate the axios.get() function using the code below, however TypeScript is returning an error stating "argument of type '{ data: expectedResult }' is not assignable to parameter of type 'AxiosPromise<{}>'". Can ...

In the world of GramJS, Connection is designed to be a class, not just another instance

When attempting to initialize a connection to Telegram using the GramJS library in my service, I encountered an error: [2024-04-19 15:10:02] (node:11888) UnhandledPromiseRejectionWarning: Error: Connection should be a class not an instance at new Teleg ...

Trouble with using the date pipe in Angular specifically for the KHMER language

<span>{{ value | date: 'E, dd/MM/yyyy':undefined:languageCode }}</span> I am facing a challenge where I need to identify the specific locale code for the KHMER language used in Cambodia. Despite trying various cod ...