Are there any alternatives to the Safe Navigation Operator specifically for TypeScript files with versions less than 3.7?

After updating my TypeScript to version 3.2, I found myself in need of an alternative to the safe navigation operator. It makes my code very lengthy when I have to check for 3 to 4 keys.

For example, if I need to check for Obj.key1.key2,key3, then my code ends up looking like this:

if((Obj != undefined || Obj!= null)&&
   (Obj.key1 != undefined || Obj.key1!= null)&&
   (Obj.key1.key2 != undefined || Obj.key1.key2!= null)&&
   (Obj.key1.key2.key3 != undefined || Obj.key1.key2.key3!= null)&&
   Obj.key1.key2.key3 == some_value){
    //do something...
}

Answer №1

This new functionality, known as "optional chaining" in MDN and other ECMAScript documentation, has officially advanced to Stage 4 (ready for incorporation) in December 2019 as part of ES2020. Browser support currently stands at 90.86% globally as of October 2021 according to caniuse.com.

Typescript's inclusion of optional chaining was introduced on November 5, 2019, almost two years prior to this response as discussed within its issue on Microsoft/TypeScript#16. Compilation options are available in Webpack 5 or Babel's env for ES2020. For the majority of developers, updating to more recent versions of TypeScript tooling is recommended over using an alternative implementation.

If modern tooling is not viable, a helper method will be required; since optional chaining cannot be directly polyfilled due to being a language feature. Similarly compatible alternatives can be found in various common libraries:

Answer №2

In TypeScript versions prior to 3.7, I have created a custom function that can serve as an alternative to the safe navigation operator.

/*
  This function is designed to check if an object is accessible and return its value if it is.
  It returns false if the object is not accessible (i.e., if the value is null or undefined).
  For example, if you want to verify if "obj.key1.key2" is accessible and perform a value check:
  if (isAccessible(obj,["key1","key2"]) == some_value){
    ...do something...
  }

  You don't need to manually check for null and undefined at each key level.

  NOTE: This function serves as an alternative to the "SAFE NAVIGATOR OPERATOR (?)" in TypeScript versions prior to 3.7
*/

isAccessible(data, keys, start=0) {
  if (start == 0 && (data == null || data == undefined)) {
    console.warn("data",data);
    return data;
  } else {
    if (data[keys[start]] == null || data[keys[start]] == undefined) {
      console.warn("Object valid till", keys.slice(0,start),keys[start],"undefined");
      return data[keys[start]];
    } else {
      if (start + 1 >= keys.length) {
        // console.log("output",data[keys[start]]);
        return data[keys[start]];
      }
      return this.isAccessible(data[keys[start]], keys, start + 1);
    }
  }
}

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

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

What causes the distinction between resolve("../....") and resolve("foo")?

Because of various node versions and incompatible ABIs, I have to load a C++ addon relatively since they are located in different locations with different ABI versions. However, the issue I am facing is quite simple. Why do these two calls produce differe ...

Discover the process of accessing and setting values in Angular 8 to easily retrieve and manipulate data from any page!

Greetings! I am currently utilizing Angular 8 and I have a query regarding how to access the set value in any given page. Here is a snippet of my code: class.ts export class testClass { get test():string{ return this.sexe; } ...

Notifying locally in Ionic 3 every couple of hours

I have a concept for my app where users can choose to receive notifications every 3 hours. The challenge is setting up a toggle on the HTML that, when activated, prompts the user to input the first time they eat in a day. From there, the app will send remi ...

Div with inline-block elements nested inside

My attempt at creating a grid using display:inline-block with divs was successful when positioning the divs next to each other. However, once I added elements inside the divs, the parent div started moving down. Here is the code snippet that caused the is ...

Is there a left and right margin when incorporating Bootstrap grid?

Currently, I am working on developing an Angular application and utilizing Bootstrap columns to easily format and space my page. However, I am facing an issue where there seems to be some unwanted margin around the element even though I have applied col-lg ...

Ways to consistently monitor an API and terminate the monitoring if specified criteria are not satisfied

Currently, I have a piece of code that checks if there are any pending services greater than 0 and then calls an HTTP API to get the new status. The code looks like: counter = 1; getDetatils(){ this.myService.getDetails().subscribe(services => { ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

Using CSS to create hover effects for specific classes of elements

Is there a way to make the button change color on hover when hovering over anywhere in the navigation bar (.topNav) instead of just when hovering over the individual button elements (.top, .middle, .bottom classes)? I tried using span to achieve this, but ...

What is the procedure for utilizing the knex object as a data type?

Looking to create a function that takes the knex instance as a parameter. Attempting to achieve this through: import knex from "knex"; export async function createTestTable(_knex: ReturnType<knex>) { ... } Encountering the error Cann ...

Ensuring the Angular Material bottom sheet (popover) stays attached to the button

Recently, I've been working on an Angular project where I successfully integrated a bottom sheet from Angular Material. However, I encountered an issue when trying to make the opened popup sticky to the bottom and responsive to its position, but unfor ...

Adding up nested arrays based on their respective indices

If I have two nested arrays within a corresponding array like this: const nums = [ [4, 23, 20, 23, 6, 8, 4, 0], // Each array consists of 8 items [7, 5, 2, 2, 0, 0, 0, 0] ]; How can I add the values based on their indexes? Expected Result: ...

Creating a Custom TreeView in VS Code using JSON data

My goal is to create a TreeView using data from a JSON file or REST call, with custom icons for each type of object (Server, Host, and Group). I want to implement configuration.menu similar to the dynamic context menu discussed in this thread. I am relati ...

What is the process for integrating a third party API certificate into my Heroku application?

When my backend service calls a third-party API (Kamer van koophandel) to retrieve data, it requires a certificate to be set. It functions correctly locally, but upon pushing to Heroku, the following error occurs: Warning: Ignoring extra certs from `Privat ...

What is the process for integrating a JOI validator with a Firebase function?

Is there a way to incorporate JOI validator into Firebase functions as middleware? When calling a Firebase function, it looks something like this: exports.createUserAccount = region("europe-east1").https.onCall(createAccount); // createAccount is ...

Angular 2 is throwing an error stating that the argument 'ElementRef' cannot be assigned to the parameter 'ViewContainerRef'

I'm developing an Angular 2 application with angular-cli, but when I include the following constructor, I encounter the following error: Error Argument of type 'ElementRef' is not assignable to parameter of type 'ViewContainerRef&apos ...

When moving to a different route inside the router.events function, the browser becomes unresponsive

Within my top navbar component, I have set up a subscription to the router events: this.router.events.subscribe(event => { if (event instanceof RoutesRecognized && this.authService.isLoggedIn()) { // additional custom logic here: ...

Issue encountered: Unable to locate module due to error: Unable to resolve 'crypto' in 'C:UsersmonkeDocumentsEpiconesb-ui ode_modules eflect-metadata'

I am encountering an issue with the reflect-metadata package while working on Angular 13. When attempting to use reflect-metadata, I am getting a strange error message stating "Module not found: Error: Can't resolve 'Crypto' in '*\ ...

Using TypeGraphQL with Apollo Server for File Uploads

What I'm Striving to Achieve I am attempting to implement file uploads using typegraphql (a wrapper on Apollo Server). I have created a basic resolver that is supposed to receive a file upload and save it to the server. The Code I'm Using This ...

Encountering build:web failure within npm script due to TypeScript

Our project is utilizing the expo-cli as a local dependency in order to execute build:web from an npm script without requiring the global installation of expo-cli. However, when we run npm run build:web, we encounter the following exception. To isolate th ...