Error code 2532 occurs when trying to access an object using square brackets in TypeScript

Encountered the

ts error: Object is possibly 'undefined'.(2532) 
issue while trying to access the value of a field within an object, where the object key corresponds to a value in an Enum.

Below is a concise example to showcase this problem:


enum Fruits {
   Apple = "Apple",
   Bannana = "Bannana",
   // and more…
}

type fruitsInfo = {
  [key in Fruits]? : { cal: number, carb: number, }
};

type numberOfFruits = {
  [key in Fruits]? : number
};

function makeMeal(info : fruitsInfo, fruits : numberOfFruits) {
   for (const keyStr in info) {
      const key = keyStr as Fruits;
      if (fruits[key] > 2) {
         console.log("You eat a lot!")
      }
   }
}

Run on TS Playground.

Although this is just a simple demonstration, my actual code is more complex. It's important that I maintain the structure of fruitsInfo and numberOfFruits with the ?, since not all keys may be present in the objects.

One thing is certain: any key existing in info will also exist in fruits

Answer №1

It seems like your code is throwing an error:

Object is possibly 'undefined'.(2532)

The issue lies in this section of your code:

      if (undefined > 2) { // <! The value 'undefined' cannot be used here.(18050)
         console.log("You eat a lot!")
      }

To fix this error, you can either specify that the variable is not `undefined` using the `!` clause or ensure it is of type `number`:

      if (fruits[key]! > 2) { // say that it's not `undefined`
         console.log("You eat a lot!")
      }      
      if (Number(fruits[key]) > 2) { // convert it to number (NaN)
         console.log("You eat a lot!")
      }

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

Issue with react-router-dom loader defer type issue

I attempted to troubleshoot the issue with data loading by incorporating defer in the loader function. I am unsure how to specify the postResponse type, which represents the actual response data. Even after experimenting with type casting and other m ...

How to enable Autocomplete popper to expand beyond the menu boundaries in Material UI

Within my Menu component, I have an Autocomplete element. When the Autocomplete is clicked, the dropdown list/Popper appears but it's confined within the Menu parent. How can I make it so that the Autocomplete's dropdown list/Popper isn't re ...

Designing a personalized mat-icon using the Github SVG

Trying to create a unique custom SVG mat-icon by loading the SVG directly from Github. My initial attempt using DomSanitizer was documented in this article, and it successfully loaded the SVG via HttpClient. Now, I am attempting to achieve this directly t ...

Is it possible to enhance an interface by integrating the characteristics of a constant?

I am currently working on customizing a material-ui v4 Theme. Within our separate @our-project/ui package, we have the following: export declare const themeOptions: { palette: { // some colors missing from Palette } status: string; // other pro ...

The MUI DataGrid's onCellEditStop event triggers when a cell's value is

When using MUI DataGrid, I encountered an issue where the value of a previously edited cell changes when editing another cell. I read that using onCellEditCommit as a solution, but since it's deprecated, I'm seeking an alternative fix. const ha ...

Creating a TypeScript type or interface that represents an object with one of many keys or simply a string

I am tasked with creating an interface that can either be a string or an object with one of three specific keys. The function I have takes care of different errors and returns the appropriate message: export const determineError = (error: ServerAlerts): ...

Vue.js is unable to recognize this type when used with TypeScript

In my code snippet, I am trying to set a new value for this.msg but it results in an error saying Type '"asdasd"' is not assignable to type 'Function'. This issue persists both in Visual Studio and during webpack build. It seems like Ty ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

Having trouble with React npm start: 'No chokidar version found' error occurring

After cloning my React-Typescript app on Github Pages and attempting to make some changes, I encountered an issue. Despite running npm install to install all dependencies, when I tried to run npm start, I received the following error message: https://i.st ...

Why is it that TypeScript does not issue any complaints concerning specific variables which are undefined?

I have the following example: class Relative { constructor(public fullName : string) { } greet() { return "Hello, my name is " + fullName; } } let relative : Relative = new Relative("John"); console.log(relative.greet()); Under certain circum ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

What is the best way to output a JSX element using an inline switch statement?

I have been attempting to use an inline switch in order to return an element, but all I am getting is an empty <span> </span>. What could be the issue here? getRowTdForHeader: (header: string, entry: response) => { return (< ...

Having trouble using the 'in' operator to search for 'Symbol(StrapiCustomCoreController)' while transitioning Strapi to TypeScript

I'm in the process of converting my strapi project to typescript. I've updated all strapi packages to version 4.15.5 and converted the files to ts extension. However, upon running strapi develop, I encounter the following error: [2024-01-03 10:50 ...

Will the async pipe activate onPush change detection in Angular?

I have searched various sources for the question above, but I am finding conflicting answers. For example, on Angular University's website, it is mentioned that change detection is triggered when the async pipe receives a new observable value. However ...

Angular firebase Error: The parameter 'result' is missing a specified type and is implicitly assigned the 'any' type

I have encountered an issue with the code I am working on and both the result and error are throwing errors: ERROR in src/app/login/phone/phone.component.ts(48,75): error TS7006: Parameter 'result' implicitly has an 'any' type. s ...

Convert the Date FR and Date US formats to ISO date format

There is a function in my code that accepts dates in different formats. It can handle two formats: 2022-06-04 or 04/06/2022 I want all dates to be in the format: 2022-06-04 For instance: public getMaxduration(data: object[]): number { data.forEach((l ...

How can I set the default bindLabel for a dropdown in @ng-select/ng-select when the self change event occurs in Angular

I have a scenario where I need to set the default value to null in the ng-select. If the user selects an option from the dropdown first, then on the change event it should check if the Amount model is not null or blank. If the Amount model is blank, then ...

When refactoring docxtemplater on the server, the request JSON object is no longer accessible in the doc.setData() method

I've been working on refactoring some code in my Node server to remove docxtemplater. The req.body json object is functioning properly and I can even print it inside the doc.setData() method. However, when I try to launch the server, I encounter this ...

Retrieve the 90 days leading up to the current date using JavaScript

I've been searching for a way to create an array of the 90 days before today, but I haven't found a solution on StackOverflow or Google. const now = new Date(); const daysBefore = now.setDate(priorDate.getDate() - 90); The result I'm looki ...

Displaying a segment of information extracted from a JSON array

I'm currently tackling a project that involves using React, Redux, and TypeScript. Within the JSON file, there is a key-value pair: "data_start": "2022-09-02" Is there a way to display this date in a different format, specifical ...