Utilizing the optional chaining operator with a variable in TypeScript: A guide

I have come across this code snippet and I am trying to figure out how to use a variable for optional chaining operator in order to avoid the error related to type 'any'. The goal is to extract numbers from the value key of an object. Can someone guide me on how to achieve this?

    function fun(i?: number) {
        console.log(i)
    }

    const variable = { min: { value: 1, name: 'google' }, max: {value: 2, name: 'apple'} }
    const variable2 = { min: { value: 1, name: 'google' } }
    const variable3 = { max: {value: 2, name: 'apple'} }

    fun(variable?.min.value) // working => 1
    fun(variable?.max.value) // working => 2
    fun(variable2?.min.value) // working => 1
    fun(variable2?.max.value) // working => undefined
    fun(variable3?.min.value) // working => undefined
    fun(variable3?.max.value) // working => 2

    Object.keys(variable).forEach((key) => {
        fun(variable?.[key]?.value) // working but with error Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ min: { value: number; name: string; }; max: { value: number; name: string; }; }'.
    })

Answer №1

The issue here lies not in optional chaining, but rather in how Object.keys functions. According to Typescript's assumption that an object may have more keys than known at compile time, the type of key is considered to be string and not keyof variable. To address this, you must inform the TS compiler that all keys are indeed known at compile time by using:

Object.keys(variable).forEach((key) => {
  fun(variable[key as keyof typeof variable].value) 
})

Since you're already treating variable as a non-null variable within Object.keys, there's no need to use optional chaining on it repeatedly. Furthermore, when casting key into keyof typeof variable, you're essentially asserting its existence, allowing you to eliminate optional chaining before ?.value as well.

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

Utilizing event delegation for JavaScript addEventListener across multiple elements

How can I use event delegation with addEventListener on multiple elements? I want to trigger a click event on .node, including dynamically added elements. The code I have tried so far gives different results when clicking on .title, .image, or .subtitle. ...

jQuery: Trouble with executing the Ajax request

I am working with Jquery to track the number of clicks and keypresses by users. $(document).ready(function(){ var countClick = 0; var keyClick = 0; $("body").mousedown(function(){ countClick ++; }); $("body").keypre ...

Assign characteristics to particular items within an array

When working with AngularJS/Javascript, I have an array of objects that each contain a date. My goal is to order these objects by date and then add an attribute to the last object that has a specific datetime. If there are two objects with the same date, t ...

Strategies for efficiently updating specific objects within a state array by utilizing keys retrieved from the DOM

I am trying to figure out how to use the spread operator to update state arrays with objects that have specific ids. Currently, I have an array called "todos" containing objects like this: todos: [ { id: "1", description: "Run", co ...

Uh oh! An error occurred when trying to submit the form, indicating that "quotesCollection is not defined" in Mongodb Atlas

Displayed below is my server.js file code, along with the error message displayed in the browser post clicking the Submit button. const express = require('express'); const bodyParser = require('body-parser'); const MongoClient = require ...

Is there a Javascript syntax similar to a "method group"?

One interesting syntactical feature of C# is the ability to pass in a "method group" to a function expecting a delegate type, like this: "string".Count (Char.IsWhiteSpace); This is much cleaner compared to using an anonymous function: "string".Count (c ...

Transitioning from using sendfile() to sendFile() function within the Express framework

Here is the code snippet I am using: router.get('/image',(req,res,next)=>{ const fileName = "path_to.jpg" res.sendfile(fileName,(err)=>{ if (err) { next(err); } else { console.log('Sent:', fileName); } ...

Navigating cross domain JSONP cookies in IE8 to IE10 can be a real headache

For reasons completely out of my control, here is the current scenario I'm faced with: I have a product listing on catalog.org When you click the "Add to Cart" button on a product, it triggers an AJAX JSONP request to secure.com/product/add/[pro ...

Vue 2.0 custom filter not producing any output

I am attempting to create a customized filter that identifies and returns the items that correspond to a given input. It functions effectively with basic arrays like ['Apple', 'Banana', 'Cupple'], but encounters difficulty whe ...

An array of size 10x10 where each new array replaces the previous one

I'm currently working on a function that generates a 10 by 10 array filled with random D's and E's. Below is the code snippet: function generateTenByTenArray(){ var outerArray = []; var innerArray = []; for(var i = 0; i < 10 ...

Modify multiple elements in a nested array by utilizing the $set and $push operators

Here is an example of the Workspace document that needs box positions updated when dragged and dropped on the front end. { "_id": ObjectId("5eaa9b7c87e99ef2430a320b"), "logo": { "url": ".../../../assets/logo/dsdsds.png", "name": "testUpload" }, "n ...

Automated shopping cart integration script for Selenium

Hey there! I'm diving into the world of Selenium scripting and could use a hand. I have a website where users can purchase event tickets. My goal is to create a script that will automatically check for a specific price when a ticket becomes available ...

Updating Dropdown Selection in Angular 9 and 10

Is there a way to set attributes to "Selected" in HTML options based on a condition from a *ngFor loop in response.body of the component ts file? Below is the dropdown code: <select [(ngModel)]="customer.id"> <option *ngFor="let location of lo ...

Upon selecting the correct prompt, it fails to respond when I press enter

I attempted to use a multi-search script that I found on a website. I followed the instructions given and made the necessary changes. After saving the file as an HTML document, I opened it in Chrome. However, when I type in a word and hit enter, nothing ha ...

There was an error encountered when attempting to parse the JSON data due to an unexpected token 'l' at position 0

I am attempting to display JSON values in a dropdown list that is nested inside a table. The JSON values I am working with can take the following form: var ids1 = [{"pid":"23221","des":"2321"},{"pid":"1301","des":"1301"},{"pid":"1003","des":"1003"}] va ...

What is the best way to iterate through a JSON associative array using JavaScript?

When I receive a JSON response from the server, my goal is to loop through the array in JavaScript and extract the values. However, I am facing difficulties in doing so. The structure of the JSON response array is as follows: { "1": "Schools", "20" ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

What could be the reason behind needing to refresh my Express endpoint in order to access req.headers.cookies from the frontend?

I've encountered an issue where I must refresh my express endpoint in order to properly access req.headers.cookie. Without refreshing the endpoint, console.log(req.headers.cookie) returns undefined instead of the expected value. I have attached some i ...

Exporting JSON blend files in Three.js is causing an error that says "Cannot read property 'type' of undefined."

Trying to display the default 3D cube template from Blender v2.74 in Chrome browser, I exported it as json using the threejs v1.4.0 add-on and I'm using Three.js revision 71. Referencing the documentation at , I attempted to load this json model stor ...

What measures can be taken to guarantee that a user is only able to delete designated records?

When it comes to writing SQL commands directly, it's simple to specify which records to delete using identifiers like ID. However, when dealing with webpages that contain a list of links pointing to different records (with the ID embedded as a query ...