简体   繁体   中英

TypeScript isObject & isNullOrUndefined deprecated angular

After upgrading from angular 7 to angular 10 and using TypeScript 4 or above. I started get warning deprecation of isObject() and isNullOrUndefined() functions when I run ng lint

warnings
isNullOrUndefined is deprecated: since v4.0.0 - use `value === null || value === undefined` instead.
isObject is deprecated: since v4.0.0 - use `value !== null && typeof value === 'object'` instead.

I fixed the problem by creating a my own utils.ts file in my project utils/utils.ts . I exported following two methods.

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

/**
 * custom function to supported deprecated function isObject
 * @param value any
 * @returns boolean
 */
export function isObject(value: any) {
    return value !== null && typeof value === 'object';
}

Then I updated all imports of isNullOrUndefined and isObject

From:
import { isNullOrUndefined, isObject } from 'util';
To:
import { isNullOrUndefined, isObject } from '@common/lib/utils/utils';

Instead of your isNullOrUndefined() function, I'd rather turn the logic around and use 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;  
  }
  // note, that typescript now knows that foo must be a string
  return foo.split('.');
}

see Typescript Playground Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM