Angular has deprecated the use of `isObject` and `isNullOrUndefined` in TypeScript

Upon upgrading from Angular 7 to Angular 10 and implementing TypeScript 4 or higher, I began receiving deprecation warnings for the functions isObject() and isNullOrUndefined() when running ng lint

warnings
The function isNullOrUndefined has been deprecated since version 4.0.0 - please use `value === null || value === undefined` instead.
The function isObject has been deprecated since version 4.0.0 - please use `value !== null && typeof value === 'object'` instead.

Answer №1

Why stick with the isNullOrUndefined() function when you can switch things up by using a type predicate:

function isDefined<T>(value: T | undefined | null): value is T {
  return value !== undefined && value !== null;
}
function bar(foo: string | undefined | null) {
  if (!isDefined(foo)) {
    return undefined;  
  }
  // With this type predicate, TypeScript recognizes that foo must be a string
  return foo.split('.');
}

Check out this Typescript Playground Example

Answer №2

To solve the issue at hand, I took the initiative to create my own file called utilities.ts within the project structure under utils/utilities.ts. In this file, I defined and exported two essential methods.

File utils/utilites.ts
/**
 * Function created to replace deprecated isNullOrUndefined function
 * @param value any
 * @returns boolean
 */
export function checkIfNull(value: any) {
    return value === null || value === undefined;
}

/**
 * New function introduced as a replacement for deprecated isObject function
 * @param value any
 * @returns boolean
 */
export function verifyObject(value: any) {
    return value !== null && typeof value === 'object';
}

I proceeded by making necessary changes to all import statements involving checkIfNull and verifyObject

From:
import { checkIfNull, verifyObject } from 'util';
To:
import { checkIfNull, verifyObject } from '@common/lib/utils/utilities';

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

Is there a way to include a message in browser.wait() without altering the preset timeout value?

I have encountered an issue with my code: browser.wait(ExpectedConditions.presenceOf(elementName)); Unfortunately, this often fails and only provides the vague message "expected true to be false", which is quite frustrating. When it fails, I need a more ...

Error message: When working with Protobuf, an uncaught reference error occurs because the 'exports

Currently, I am in the process of configuring protobuf to work with typescript. According to the official Google Documentation, all that is needed is to execute npm install google-protobuf and then to include require('google-protobuf'). Unfortu ...

Is it necessary to bootstrap every individual component in Angular 2?

Is it necessary to bootstrap each component individually in this code snippet? import { bootstrap } from '@angular/platform-browser-dynamic'; import { AppComponent1 } from './app.component1'; import { AppComponent2 } from './app ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

What is the best way to retrieve information utilizing Http.get within my project?

I have a TypeScript file containing user data: File path: quickstart-muster/app/mock/user.mock.ts import {User} from "../user"; export const USERS:User[]=[ new User(....); ]; I have a service set up at: quickstart-muster/app/services/user.service.ts ...

The combination of ASP.Net Core 1.1 and Angular 2 in a PUT request triggers a No Access Control

In my ASP.Net Core 1.1 backend, CORS has been enabled as shown below: public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddDbContext<WebAPIDataContext>(options => { options.UseMyS ...

The function `find()` will not provide any data, it will only output `undefined`

I am trying to extract the `s_id` field from this JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "s_id": "11E8C70C8A5D78888E6EFA163EBBBC1D", "s_serial": " ...

Oops! The program encountered a TypeError stating that it cannot read the property 'open' since it is undefined

Using Angular 6, I have implemented an API call in a service and subscribed to it in my controller. The data is successfully received, but I want to restructure it in the controller so that I can later pass it into a Chart JS chart. Here is the code snipp ...

What is the best way to change the name of an imported variable currently named `await` to avoid conflicting with other variables?

Here is the given code snippet: import * as fs from 'fs'; import {promises as fsPromises} from 'fs'; // ... // Reading the file without encoding to access raw buffer. const { bytesRead, buffer as fileBuffer } = await fsPromises.read( ...

Situations in which the OnPush ChangeDetectionStrategy may not be the best

After extensive research, I discovered an intriguing performance enhancement technique in Angular: setting ChangeDetectionStrategy to OnPush. This method can effectively reduce the number of modifications within an Angular App. However, are there specific ...

Leverage the JSON Web Token module within a Chrome extension

Currently in the process of developing a chrome extension but encountering an issue with loading the json web token node module in my Node.js setup. background-script.ts import jwt from 'jsonwebtoken'; // import * as jwt from '../node_mod ...

Issue: The inject() function can only be executed within an injection context

Even after following the most recommended solutions online, I am still facing an issue that says Error: inject() must be called from an injection context. In addition to this error, I am also receiving multiple warnings such as: Warning: ###/src/ap ...

Callback after completion of a for loop in Angular TypeScript

During the execution of my javascript async function, I encountered a situation where my printing code was running before the div creation. I needed to ensure that my print code would run only after the completion of the for loop, but I struggled to find a ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...

I designed a dropdown menu with a searchable <mat-select> feature, where selecting an item is automatic when a space bar is pressed in the search box

Description : I have implemented a dropdown list using element that contains a list of items along with a search field. This allows users to easily search for specific items in the list instead of manually scrolling through a long dropdown menu. They can ...

"Null value is no longer associated with the object property once it has

What causes the type of y to change to string only after the destruction of the object? const obj: { x: string; y: string | null } = {} as any const { x, y } = obj // y is string now ...

What is the best method for organizing an array of objects based on their subobjects?

When developing a web app's back-end with TypeScript, I've found intersection types to be incredibly beneficial for optimizing SQL queries. Imagine having the following tables: User userId: number userEmail: string Post postId: number userId: ...

Fetching properties from an array of components

Hello, I'm currently working on a React component and facing an interesting challenge. Let's say I have an array structured like this: let data: {title: ReactNode}[] = [ {title: "test1"}, {title: <Component1 title="test2& ...

An issue with Angular 7 and Form Arrays is causing a button within a form group to remain disabled even when the associated form group is not valid, resulting in an undefined

I am working on a form array that generates form controls for each row along with a button. The challenge I'm facing is to disable the button associated with a row if the form group related to that row in the form array is not valid. Here is the but ...

Tips for adjusting the dimensions of images in the primeng editor

Currently working on an Angular 8 application that utilizes the prime ng editor. I am looking to set limits for image size and dimensions before uploading via the upload image button, but encountering difficulties in implementing this feature. https://i.s ...