简体   繁体   English

TypeScript isObject & isNullOrUndefined 已弃用 angular

[英]TypeScript isObject & isNullOrUndefined deprecated angular

After upgrading from angular 7 to angular 10 and using TypeScript 4 or above.从 angular 7 升级到 angular 10 并使用 TypeScript 4 或更高版本后。 I started get warning deprecation of isObject() and isNullOrUndefined() functions when I run ng lint当我运行ng lint时,我开始收到isObject()isNullOrUndefined()函数的警告弃用

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 .我通过在我的项目utils/utils.ts创建我自己的utils.ts文件解决了这个问题。 I exported following two methods.我导出了以下两种方法。

File utils/utils.ts文件 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然后我更新了isNullOrUndefinedisObject所有导入

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 :而不是你的isNullOrUndefined()函数,我宁愿扭转逻辑并使用类型谓词

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参见Typescript Playground 示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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