You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() {
  let obj = {
    fName: "ali",
    LName: "sarabi",
    age: "19",
  }
  let fieldName = prompt("field");
  alert(obj[fieldName]);
}

I encountered an issue with the code above where alert(obj[fieldName]) is giving me an error specifically related to fieldName:

The error message is 'let fieldName: string | null Type 'null' cannot be used as an index type.ts(2538)'

Can anyone assist me in resolving this error?

Answer №1

Make sure to verify if the variable fieldName is defined before triggering an alert.

Include this conditional statement:

if(fieldName !== undefined) {
// alert(obj[fieldName])}

Answer №2

Insight: When working with Typescript, it is important to remember that it is a strictly typed language. This means that errors can occur at compile time if the correct types are not used. In the given scenario, using the returned value of prompt() as an index can lead to potential issues because array indexes cannot be null, while the return value from prompt() can be null. To handle this situation, you must specify to the compiler that if fieldName is null, then use an empty string instead. By doing this, you ensure that the index will never be null.

Here are two alternatives to consider:

onClick(){
    let obj={
      fName:"ali",
      LName:"sarabi",
      age:"19",
    }
    let fieldName = prompt("field") || "";
    alert(obj[fieldName]);
}

or try this approach:

onClick(){
    let obj={
      fName:"ali",
      LName:"sarabi",
      age:"19",
    }
    let fieldName = prompt("field");
    alert(obj[fieldName?fieldName:""]);
}

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

Use 'data-toggle='button'' in Angular component only once the condition is validated

Looking to verify a certain condition upon clicking, and if it evaluates to true, toggle the element that was clicked <div class="btn-group btn-group-toggle" data-toggle="buttons"> <label class="btn btn-secondary active" (click)='example ...

Displaying an error message following the dynamic retrieval of the input field's value

How can I display an error message when a specific field with a value of 0 is not filled out in my Angular reactive forms? In my form, I have added a dropdown which is mandatory and I have implemented validators to ensure it is required. The validator work ...

Incorporate jQuery on elements that are dynamically loaded after the page has finished loading

I need to determine if a dynamically added button is enabled or disabled. How can this be achieved? My goal is to display a message when the button is disabled and remove it when the button becomes enabled. This is my current code: jQuery(document).read ...

Challenge encountered with Promise failing to resolve despite multiple retry attempts

I've been struggling with Promises as a beginner for the past few days. I need to make an API call and check if there is a response. If not, I have to retry calling the API a configurable number of times. I attempted the following code, but I'm u ...

What is the process for linking my Next.js application with MongoDB Compass?

Currently, I am working on a project in Next.js called NetMapper where I am developing a web interface for the CLI tool nmap. My main focus right now is creating Sign In/Sign Up forms and storing user information in MongoDB Compass. Despite trying various ...

Using Vue.js to bind data in two directions by using an object with v-for

I can't seem to get input data properly bound to object properties. When I try to iterate through an object to create input fields based on its attributes, the v-model data binding doesn't seem to be working as expected. Even with the code below, ...

The amazingly efficient Chrome quick find feature, accessible by pressing the powerful combination of Ctrl + F, ingeniously

Currently using Google Chrome version 29.0.1547.62 m. I've employed the CSS attribute overflow set to hidden on the parent element, which renders some of my DIV elements hidden from view. Additionally, these concealed DIV elements are adjusted in pos ...

Techniques for concealing a button when the "disabled" attribute is set to "true"

The button is currently disabled, however, I intended for it to be hidden from the UI when the disabled condition is met - <button ion-button block class="button-color-blue" [disabled]="true" (click)="closePage()"> Cancel </b ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...

How come props do not get updated along with state changes?

I've encountered an issue where the state of a component being passed into another component as a prop is not updating correspondingly. Various attempts have been made to resolve this, including placing it in the return function and updating the "low ...

Removing validators in Angular forms after submitting the form and resetting it

I am currently working on an Angular app that includes a form. Whenever I click the submit button, the reset() function gets triggered on the form. However, after the reset() function is called, all inputs are marked as having errors. I have tried using fu ...

Using whitespace to format a document.write in JavaScript

I'm in the process of creating a dynamic table using JavaScript and a set of objects. I've managed to structure it, but now I require some extra white space between them, almost like tabbing them out. How can I achieve this efficiently with my cu ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

Utilizing JSON in a d3.js application within a Rails environment

I have been exploring the gem gon in order to generate JSON data from my Rails database. I have successfully managed to display this data in an alert, but now I am looking to visualize it using d3.js. Within my database named "users" with columns (name:st ...

When sending a response using res.send, it is not possible to include all properties of

I'm working with an API controller method that looks like this: let object = { "key1": "value1", "key2": "value2", "arrayKey": [ { "arrKey": "arrValue", "arrKey1": 1 } ] } export const foo = ...

disable caching for xmlhttp request

One issue I am facing is with a JavaScript function that retrieves JSON data via an Ajax request. The problem I'm encountering is that the browser starts caching the response to this request, which means I am not getting the most recent data from the ...

Encountering module not found error in Angular 2 after running npm install

I am facing an issue with my Angular 2 application while trying to integrate the angular2-autosize component following the steps outlined on its GitHub page (https://github.com/stevepapa/angular2-autosize). I executed the command below: npm install angula ...

Guide to resolving the issue of error Type 'void[] | undefined' cannot be assigned to type 'ReactNode'

I am attempting to map the data Array but I am encountering an error: Type 'void[] | undefined' is not assignable to type 'ReactNode'. Can someone please assist me in identifying what I am doing wrong here? Below is the code snippet: i ...

Add a unique CSS style to both text and image using anchor tags

Why isn't the hover effect of color transition and underline being applied to the image? It seems to only work for text. While I understand that the color transition may require a change in image color, shouldn't the underline still occur? This ...

Apply criteria to an array based on multiple attribute conditions

Given an array containing parent-child relationships and their corresponding expenses, the task is to filter the list based on parents that have a mix of positive and negative expenses across their children. Parents with only positive or negative child exp ...