Let's define JSON data using Record<> and verify the presence of a specific key

When my backend sends a JSON object with id strings mapping to data, I make use of the Typescript type Record. Since some ids may not exist, I define it as:

let data: Record<string, number | undefined> = {
    'asdf': 1
};

To process this data and check if a key exists, I do:

const id = 'asdf';
if (id in data) {
    const id_data = data[id];
    console.log(id_data + 1); // compiler warns it might be undefined
}

The compiler provides better support for other patterns. So, I'm unsure if this is the best way to handle my backend response. Any suggestions?

Answer №1

It is common to encounter this issue because using id in data alone does not ensure that id_data = data[id] will have a defined value. The key may exist in the object but its corresponding value could still be undefined.

To address this, you must explicitly check the value itself.

const data: Record<string, number | undefined> = {
  "asdo2q" : 253,
  "s398dd" : 132,
}

const id = 'asdf';
const id_data = data[id];
if (id_data !== undefined) {
    console.log(id_data + 1); // now it works
}

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

Ways to verify if an item is an Express object?

Currently, I am utilizing typescript to verify whether an app returned by the Express() function is indeed an instance of Express. This is how I am attempting to accomplish this: import Express from "express" const app = Express() console.log( ...

Reading JSON containing German special characters

I've hit a roadblock while trying to use $.parseJSON in jQuery to parse a translation file. The issue arises with this particular line: "[„Alle“, „Spezifische Tage“]" It appears that parseJSON is having trouble with the German quotation mark ...

What is the reason for the regeneration of the 2D array?

I have a method called generateWeights() that retrieves random values in an array; And a method named learn() that calls the changeWeights() method to alter the values in the array. Expected: Prior to invoking the learn() method, I anticipate receiving an ...

What is the best way to handle null properties when using JsonSerializable::jsonSerialize()?

Consider a scenario where we need to serialize an object with nested objects: class User implements \JsonSerializable { private $name; private $email; private $address; public function jsonSerialize() { return [ ...

Python authentication system - Verifying user passwords stored in a JSON database

I have been designing a login interface to collect user names and passwords. Once this aspect is functioning properly, I intend to integrate it into a larger project that I am currently developing. My current issue revolves around validating passwords for ...

Utilizing JQueryMobile, JSON, and transferring data to a fresh webpage

Hi there, hope everyone is doing well and having a great time coding! I have a question regarding passing a URL rel to a new page for future use. Let me explain with an example instead of going on and on. Imagine you are on page "A" and you have a link t ...

Issues encounteted when trying to implement Auth0/Angular2-Jwt in Angular 5 environment

There is a specific function in Angular2-JWT that I am trying to use to Show/Hide links based on the logged user token stored in localStorage. The function is called tokenNotExpired(). I have been exploring different approaches to implement conditional s ...

Generating a JSON file from a List in Flutter using GetX package: A step-by-step guide

How can I utilize the GetX package in Flutter to generate JSON from multiple lists? The lists are sourced from the Episode5.dart file and displayed in the MyApp file where a JSON Generate Button is located. Upon clicking the button, I aim to create JSON us ...

Typescript: The art of selectively exporting specific types

As I develop a Typescript component library, the API consists of two named exports: the component itself and a helper function to create an object for passing as a prop. The process is straightforward. For this library, I utilize an index.ts file as the m ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

Encountered a Milvus 2 Node.js SDK issue: "Error: TypeError: Class extends value undefined is not a constructor or null"

I'm currently developing an application using Nuxt.js and have opted for Milvus as the database. I'm aiming to implement a similarity search feature, but I've hit a roadblock with an error popping up in the browser console. The code snippet ...

Enhancing Form Fields Dynamically using AJAX and JSON

I'm trying to update specific fields in my form after fetching data from a database using AJAX and JSON. Here is the code snippet: In my form: <div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( ' ...

How can I execute a HTTP POST request in Node.js using MongoDB and Mongoose?

I have completed my schema setup and now I am looking for guidance on how to perform an HTTP POST request. I am currently utilizing MongoDB with the Mongoose framework. By implementing this, I aim to view the JSON data I have posted when accessing localhos ...

Create an object of a class with the ability to dynamically determine the file path during

What is the best way to create an instance of a class (with an empty constructor), like this: In file api/EmptyClass1.ts, we have: export default class EmptyClass1 { } and, in file api/EmptyClass2.ts, we have: export default class EmptyClass2 { } I ...

Changing numeric key names within nested JSON structures using Python

I am attempting to modify the keys of JSON data by left padding them with a constant string if the key consists only of numbers. input_json = {'key1': {'2': 'value2', 'key3': {'key4': 'value4', &a ...

Accessing JSON information to retrieve a specific key

Here is an example of the json output data generated when creating a JIRA ticket from the command line using the curl command. {"id":"123456","key":"ABCD-123","self":"http://abcd.com/rest/api/2/issue/123456"} I am trying to extract the value "ABCD-1234" ...

What method can we use to verify if an object falls within a specified date range when filtering?

Looking to determine if the current filter object falls within a specific date range and return a boolean value based on that condition. However, the code provided always returns the data. Can anyone spot the error in the implementation or suggest a better ...

Conditional type/interface attribute typing

Below are the interfaces I am working with: interface Movie { id: number; title: string; } interface Show { title: string; ids: { trakt: number; imdb: string; tmdb?: number; }; } interface Props { data: Movie | Show; inCountdown ...

Typescript disregarding conditional statements

Looking for some assistance with a Next.JS React-Typescript application Here's my code snippet for handling the video HTML element const videoRef = useRef<HTMLVideoElement>(); useEffect(() => { videoRef !== undefined ? videoRef.current. ...

Utilizing JSON parsing with a variable in Go programming language

Is there a way to extract only the phrase "Odio los lunes" from this json data? [ [ [ "Odio los lunes", "i hate mondays", null, null, 1 ] ], null, "en" ] I want to display just Odio los lunes. ...