Angular: mysterious 'null!' syntax

As I delved into the Angular 2 source code, my curiosity was piqued by NgForOfContext<T>, located in the official repository here. What caught my attention was a particular syntax that seemed unfamiliar to me in both plain Javascript and Typescript.

The snippet of interest is as follows:

private _applyChanges(changes: IterableChanges<T>) {
    const insertTuples: RecordViewTuple<T>[] = [];
    changes.forEachOperation(
        (item: IterableChangeRecord<any>, adjustedPreviousIndex: number, currentIndex: number) => {
          if (item.previousIndex == null) {
            const view = this._viewContainer.createEmbeddedView(
                this._template, new NgForOfContext<T>(null !, this.ngForOf, -1, -1), currentIndex);
            const tuple = new RecordViewTuple<T>(item, view);
            insertTuples.push(tuple);
          } else if (currentIndex == null) {
            this._viewContainer.remove(adjustedPreviousIndex);
          } else {
            const view = this._viewContainer.get(adjustedPreviousIndex) !;
            this._viewContainer.move(view, currentIndex);
            const tuple = new RecordViewTuple(item, <EmbeddedViewRef<NgForOfContext<T>>>view);
            insertTuples.push(tuple);
          }
        });

What intrigued me the most was the use of null ! in this line:

this._template, new NgForOfContext<T>(null !, this.ngForOf, -1, -1), currentIndex);

The first argument being null, followed by a logical not (!). Upon further inspection, I realized that null is indeed a primitive type in JavaScript (and TS), making the null ! puzzling. It would seem more plausible if it were !null (not null), which would evaluate to true.

To confirm my doubts, I attempted to compile the code but encountered an unexpected error - Unexpected ). This left me perplexed as Angular functions flawlessly with such syntax. Clearly, there's something I'm missing here. Can someone help unravel this enigmatic mystery?

Answer №1

Introducing the Non-null assertion operator. This operator comes into play when dealing with values that may be null, allowing us to assert that they are indeed not null.

  var nullable: string | null = null;
  var nonNullable: string = "";

  nonNullable = nullable // Error 
  nonNullable = nullable! // Ok, we have successfully asserted its non-null status

In a somewhat counterintuitive manner, this operator can even be used to confirm that null is not null:

nonNullable = null! // Surprisingly valid because we assert null is not null 

You can play around with this concept in the TypeScript Playground through this link

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

Adding AngularJS data to JSON file for update

I'm feeling lost on where to begin with this. I am working with an AngularJS form and I need it to add the data it sends to a json file. I understand that AngularJS is client-side, so my main issue lies in figuring out how to manage the data being sen ...

The installed local Angular version is outdated compared to the current project version

I've been having trouble customizing my Angular CLI because a package I need only works with an older version of Angular. Currently, my global Angular version is 15.2.9. However, when I create a new Angular project using ng new, the package.json shows ...

Difficulties encountered when trying to create a pop-up flyover image in a Greasemonkey script

Recently, I ventured into the world of Greasemonkey scripts to learn JavaScript. My script's objective is quite simple - it enlarges a thumbnail image to a popup window when hovering over it with the mouse. Almost nearing completion, I encountered a ...

Float over a specific line in a drawing

I am looking to develop a unique rating system using css, html, and potentially js : https://i.sstatic.net/pQP79.png My goal is for the user to hover over a specific section of a circular stroke and have it fill with a particular color, all while maintai ...

The function is able to utilize window.open successfully in the beginning but encounters issues when attempting to do so at the

When using the window.open method in a function, it seems to work at the beginning of the code but not at the end. Here is an example where it works: render = function() { window.open("https://xxxx=singhi"); var yhttp = new XMLHttpRequest() ...

What methods can be used to configure Jasmine to read individual Vue component files?

I recently installed Jasmine and Vue through npm, but I'm encountering an issue when trying to import the Vue component itself, which is a .vue file. It seems to be having trouble reading the template section enclosed within <template></templ ...

Styling Descendants Conditionally in Angular 2

.parent { color: blue; } .parent * { color: red; } .child { color: black; } .grandchild { color: green; } <div class="parent"> Parent <div>Child <div>GrandChild</div> </div> </div> Imagine a scenari ...

Is it possible to view newly added text in real-time on a separate client in Node.js without relying on socket.io?

I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem ...

(Angular 2/4/5/6) Implementing multiple inner subscribe methods along with a single outer subscribe method

Trying to find a way to call two inner subscribe methods with an outer subscribe method. I am aiming to make three API calls in total, but two of them depend on the results of the first one. this.subscription = this.quoteService //1st api call .get(th ...

Use Selenium IDE to click on an element using JavaScript if the stored variable equals "Yes"

I am attempting to have Selenium IDE click on a checkbox when the stored value 'x' is equal to Yes. After trying the code below, I received an error indicating that Yes is not defined. I'm also unsure which Selenium IDE command should be u ...

A guide on retrieving values from dynamically generated table cells when a button is clicked

I am currently in the process of dynamically generating a table where each row contains a button. The goal is to be able to extract the values from the cells in the respective row when the button is clicked. HTML: <table class="table table-hover t ...

React.JS Tip: Automatically Make Alerts Disappear in 2 Seconds!

How can I make my alert automatically disappear after 2 seconds in React.JS? Currently, the alert only disappears when I manually close it using the fecharAlerta props function. import { useEffect } from "react" import { useState } from "r ...

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

Is it achievable to send information back to a Servlet from JavaScript?

I am currently working on setting up a Servlet that utilizes JDBC for database interactions. My goal is to allow users to log in through a login form and then view the list of available databases in MySQL. I am implementing this functionality dynamically ...

Navigate to a different page using Angular with a simple click

How can I implement a redirect from clicking on the "Firms" word to another component page in Angular? I have tried using routerLink="/", [routerLink]="['/']". I have imported Routes in the app.module. I have also attempted this approach: import ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

Can you explain the contrast between the two model configurations when making API calls?

Within my service file, I have a method that calls an API: getDetail(id: number): Observable<any> { return this.http.get<any>("api/detail/" + id, { responseType: 'json', observe: 'response' }) } Curren ...

Issue with running MySQL query within Javascript loop

While working with closures in this loop, I encountered a problem where only the correct data was printed on the console log, and the SQL query did not function as expected. Interestingly, the last variable of the loop was being inserted into MySQL, lead ...

Retrieve the output of a Node.js function

I have a function that extracts data from a website and displays it in the console. However, I now want to return this data so I can perform additional actions with it. Instead of using console.log(temperature), I would like to retrieve the temperature v ...

How to identify alterations in user input within Angular?

I need assistance with my search input functionality. I want to ensure that the this.searchProperties.emit is only triggered when the user interacts with the input field by touching it or making an input. The current issue is that the emit function gets ca ...