What are some techniques to ensure null checking is enforced for objects that are nested within multiple layers

Currently, I am leveraging redux sagas to fetch data asynchronously from various endpoints using a unified interface:

export interface ResponseInfo {
    data?: any;
    status: number;
    headers?: any;
    subCode?: string;
}

To ensure that null checking is enforced on the dynamic 'data' object (of type any), I require that every developer includes null checking when accessing properties. For example:

if(response.data.pizza.toppings){}

This code should result in a compile error unless proper null checks are added like so:

if(response.data && response.data.pizza && response.data.pizza.toppings){

}

While TypeScript with --strictNullChecks does not catch the lack of null checking in the aforementioned line, I wonder if tslint's no-unsafe-any rule could address this issue. Is there a built-in way for TypeScript to perform this validation independently?

Answer №1

This object can be defined using an interface with an index signature:

export interface ResponseInfo {
    data?: RecursiveObject;
    status: number;
    headers?: any;
    subCode?: string;
}

interface RecursiveObject {
    [s: string]: RecursiveObject | undefined
}

// How to use 

declare let response : ResponseInfo
if(response.data.pizza.toppings){ // Object is possibly 'undefined'

}

if(response.data.pizza){ // Object is possibly 'undefined'

}

The issue lies in response.data.pizza.toppings being a RecursiveObject, which isn't very helpful. To handle this and ensure safety, a custom type guard can be used to refine the type of the final result for more utility. (Note that a standard type guard won't suffice because RecursiveObject has no relation to string, causing a simple guard like

typeof response.data.pizza.toppings === 'string'
to narrow down to never)

function isString(o: RecursiveObject|string ): o is string {
    return typeof o === "string"
}

declare let response : ResponseInfo
if(response.data && response.data.pizza && response.data.pizza.toppings
    && isString(response.data.pizza.toppings) ){
    let s : string = response.data.pizza.toppings;

}

Somewhat lengthy but potentially beneficial.

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

Displaying a div component in React and Typescript upon clicking an element

I've been working on a to-do list project using React and TypeScript. In order to display my completed tasks, I have added a "done" button to the DOM that triggers a function when clicked. Initially, I attempted to use a useState hook in the function ...

Are you prepared for changing DropDowns?

To ensure users make a selection from a specific dropdown menu, I have implemented the following code to trigger an alert if they fail to do so: <script> function checkSelection(){ var sel = document.getElementById(' ...

When a button is clicked, the event is not triggered within a FirefoxOS application

Despite functioning perfectly on Firefox for desktop, my application encounters issues when tested on my ZTE Open C (Firefox OS 1.3). Pressing the button does not trigger any action, while onmouseup and onclick events work flawlessly. Even attempts to bin ...

The passport authentication process is malfunctioning as there seems to be an issue with the _verify function

Having an issue and could use some assistance. I am currently implementing passport in my express application. While I am able to successfully register a user, I encounter an error when trying to log in. TypeError: this._verify is not a function at Str ...

Can I use Javascript to access a span element by its class name?

Similar Question: How to Retrieve Element By Class in JavaScript? I am looking to extract the text content from a span element that does not have an ID but only a specific class. There will be only one span with this particular class. Can anyone guide ...

Detecting Eyes with the Power of JavaScript and HTML5

Looking for suggestions, steps, or algorithms for performing eye detection on 2D images using JavaScript and HTML5. I have successfully converted RGB to YCbCr color space. Now seeking assistance with eye extraction. function detectEyes(e) { var r, g ...

Struggling to retrieve the most recent emitted value from another component in Angular?

Hello everyone, I am currently attempting to retrieve the most recent updated value of a variable from the component app-confirm-bottom-sheet in the app-bene-verification.ts component, but unfortunately, I am unable to achieve this. Below is the code snipp ...

Adjust the object's width and position based on the window's width

I am currently attempting to adjust the width of a box and the position of a btn based on the size of the window. Q1. How can I eliminate the excess white space located behind the scroll bar? (I have already set it to 100%..) Q2. After clicking the ...

Angular error TS2339: The property 'before' is not found on type 'HTMLElement' / 'HTMLTextAreaElement' / etc

Objective: My goal is to reposition a div (containing a mat-select dropdown) ABOVE a mat-card-title when the user is accessing the site from a mobile device. If the user is not on a mobile device, the div should remain in its original position to the right ...

Definitions for Typescript types that describe a custom hook responsible for fetching a specific part of the Redux state

I've created a custom hook called useReduxState to fetch a specific piece of state from Redux like so: const STATE_A = useReduxState("STATE_A"); Now, I'm running into issues when trying to integrate Typescript. These are the types I a ...

The parameter failed to initialize causing the HTTP service to fire prematurely

In my project, I am utilizing Angular 10. Within the ngOnInit function, I have nested HTTP calls structured like this: ngOnInit(): void { let communetyid; this.route.data.subscribe(data => { this.route.params.subscribe(params => { ...

What is the best way to display a loading screen while simultaneously making calls to multiple APIs?

I'm currently working with Angular 8 to develop an application that retrieves responses from various APIs for users. The application is designed to simultaneously call multiple APIs and I require a loading indicator that stops once each API delivers a ...

JavaScript/TypeScript Asynchronous Filtering on AsyncIterable<T>

I am currently working with an AsyncIterable variable and I am trying to apply a filter on it. Take a look at the example below (pseudo code) - class SomeClass { private SOME_CONST= "ABCDE"; private async someFunction(): Promise<strin ...

What is the best way to monitor and record the height of a div element in a React application?

Exploring the Height of a Div I am interested in monitoring the height of a div element so that I can dynamically adjust distances based on varying screen widths. The animation should respond to changes in screen width, such as when text stacks and the he ...

Strict mode error occurs when attempting to assign a value to ngComponentOutlet that is incompatible with the type of the lazy-loaded component

I am attempting to implement lazy loading for a component in Angular 11 (strict mode) using guidance from this tutorial. Dealing with strict mode has been challenging as there are very few resources available that cater to it. The goal is to have a compon ...

What is the best way to assign a default value in mat-select when using an ngFor loop?

Is there a different approach to setting a default value in mat-select within an *ngFor loop? I'm having trouble accessing the element in the array from the loop as desired. .ts file: persons: Person[] = .. //consist of Person with name and age .htm ...

When I press the single quote, the submit button becomes disabled and stops working

image: https://i.sstatic.net/nKCTk.jpg result: https://i.sstatic.net/PE4oN.jpg When I press the '(single quote) key on my keyboard, the submit button (reply button) is not being disabled as expected. I simply want it to be disabled in order to pre ...

Guide to creating varying component sizes using ReactJS and Styled Components

Is it possible to add variation to my button based on the prop 'size' being set to either 'small' or 'medium'? interface Props { size?: 'medium' | 'small'; } How can I adjust the size of the component us ...

Guide on accessing mobile information and sim card details with Ionic 3 and Cordova on Android devices

Just started using Ionic and I'm looking for guidance on how to retrieve mobile and sim details with Ionic 3 and Cordova for Android. Any help is greatly appreciated in advance! ...

Struggling to display text content from an array onto the HTML webpage

One issue I am encountering is my inability to use Javascript to change the text within an HTML p tag. I have an HTML button with the id="knap" and a p tag with the id="answer". My goal is to change the text in the "answer" tag when the user clicks on the ...