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

Combining and Filtering Arrays of Objects with Angular

I possess: arrayBefore arrayBefore = [{name:'n1', items: [i1]}, {name:'n2', items: [i2]}, {name:'n1', items: [i3]}] I desire to craft a function: myFunction myFunction(arrayBefore) In order for it to generate: arrayAfte ...

Tips for sending code confirmation in Amazon Cognito identity using nest.js

Having some issues with implementing AWS Cognito login in Nest.js? Check out this helpful guide on token validation: https://medium.com/weekly-webtips/token-validation-with-aws-cognito-and-nestjs-6f9e4088393c. I need to add a feature where users receive ...

Derive a data type from a parameter passed to a function defined within an interface

I am working with a function defined in an interface as shown below: interface UseAutocompleteReturnValue { ... getRootProps: (externalProps?: any) => React.HTMLAttributes<HTMLDivElement>; } Within my interface, I aim to create a prop named rootP ...

Issues with Router navigation in an Ionic-Angular application

I am currently working on a straightforward application using Angular 9 and Ionic 5. The main page consists of a list of items. Here is my HTML code: <ion-header> <ion-toolbar> <ion-title>recipes</ion-title> </ion-toolba ...

Encountered an issue in Typescript with error TS2554: Was expecting 0 arguments but received 1 when implementing useReducer and useContext in React

I've encountered several errors with my useReducers and useContext in my project. One specific error (TS2554) that I keep running into is related to the AuthReducer functionality. I'm facing the same issue with each Action dispatch. I've tri ...

Issue: Troubleshooting data serialization process using getStaticProps in Next.js

I attempted to retrieve data from an API, but unfortunately encountered the following error: Server Error Error: Issue with serializing .results returned from getServerSideProps in "/". Reason: JSON serialization does not support undefin ...

Angular - Exploring the process of creating a secondary standalone build for a specific section of an application

I have created an Angular 4 (or 5) application with a specific structure as shown in the image below: Now, I need to develop a separate standalone angular application where only a selected group of Angular components from the documents directory will be i ...

I'm having trouble asynchronously adding a row to a table using the @angular/material:table schematic

Having trouble asynchronously adding rows using the @angular/material:table schematic. Despite calling this.table.renderRows(), the new rows are not displayed correctly. The "works" part is added to the table, reflecting in the paginator, but the asynchron ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

A step-by-step guide on bundling a TypeScript Language Server Extensions LSP using WebPack

Currently, I am working on a language server extension for vs-code that is based on the lsp-sample code. You can find the code here: https://github.com/microsoft/vscode-extension-samples/tree/master/lsp-sample My challenge lies in WebPacking the extension ...

Encountering issues with Angular2 App when attempting to load simulated data using a Promise causes malfunction

Looking to implement my mocked data loading using a promise, similar to the approach shown in the Angular2 Tutorial found here. Service (Mock): import { Injectable } from '@angular/core'; import { ERGEBNISSE } from "./mock-ergebnisse"; @Inject ...

Need to import a JSON file and convert it to an interface in order to ensure that all fields are included

I am facing an issue where I am attempting to parse a json file using require(). My goal is to convert it into a specific data type and have the conversion fail if the file does not contain all the necessary fields as defined by the interface. Below is my ...

TSLint has detected an error: the name 'Observable' has been shadowed

When I run tslint, I am encountering an error that was not present before. It reads as follows: ERROR: C:/...path..to../observable-debug-operator.ts[27, 13]: Shadowed name: 'Observable' I recently implemented a debug operator to my Observable b ...

What distinguishes between the methods of detecting falsy and truthy values?

While working with JavaScript / Typescript, I often find myself needing to verify if a length exists or if a value is true or false. So, the main query arises: are there any differences in performance or behavior when checking like this... const data = [ ...

Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component. ngOnInit() { this.getInspectionData(); } getInspectionData() { this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`) ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

Conditional Skipping of Lines in Node Line Reader: A Step-by-Step Guide

I am currently in the process of developing a project that involves using a line reader to input credit card numbers into a validator and identifier. If I input 10 numbers from four different credit card companies, I want to filter out the numbers from thr ...

How to disable the onChange event in PrimeNG p-dropdown?

I'm currently utilizing PrimeNG's dropdown component. Each option in the list includes an icon that, when clicked, should trigger a specific method. Additionally, I need to execute another method when the onChange event of the dropdown is trigger ...

How can I achieve this using JavaScript?

I am attempting to create a TypeScript script that will produce the following JavaScript output. This script is intended for a NodeJS server that operates with controllers imported during initialization. (Desired JavaScript output) How can I achieve this? ...

The type 'string[]' is missing the required property 'label', resulting in a typescript error

Within my codebase, I've defined a type called Person that looks like this : type Person = { value?: string[]; label?: string[]; }; Additionally, there is a promise function in my project: async function main(): Promise<Person> { const fo ...