繁体   English   中英

TypeScript isObject & isNullOrUndefined 已弃用 angular

[英]TypeScript isObject & isNullOrUndefined deprecated angular

从 angular 7 升级到 angular 10 并使用 TypeScript 4 或更高版本后。 当我运行ng lint时,我开始收到isObject()isNullOrUndefined()函数的警告弃用

警告
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.

我通过在我的项目utils/utils.ts创建我自己的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';
}

然后我更新了isNullOrUndefinedisObject所有导入

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

而不是你的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('.');
}

参见Typescript Playground 示例

暂无
暂无

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

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