繁体   English   中英

TypeScript with strictNullChecks和函数来检测空值

[英]TypeScript with strictNullChecks and function to detect null values

由于Javascript的性质,我自己检查值是否为!= null && != ''所以我创建了一个函数来检查值是否为空,如下所示:

const isEmpty = (variable: any, allowEmptyString?: boolean): boolean => {
    return variable == null || (variable == '' && !allowEmptyString);
};

问题是,其他方法不知道这意味着什么,所以我必须使用! 所有时间都要防止警告,例如:

const foo = (val?: number): void => {
    let a = 0;

    if (!isEmpty(val)) {
        a = val;
        // let a: number;
        // Type 'number | undefined' is not assignable to type 'number'.
        // Type 'undefined' is not assignable to type 'number'
    }
};

我目前的解决方案是:

if (!isEmpty(val)) {
    a = val!
}

有没有办法避免使用! 防止警告?

这是一个解决方案:

function isEmpty(variable: string | null | undefined, allowEmptyString?: boolean): variable is Exclude<undefined | null, string>
function isEmpty<T>(variable: T | null | undefined): variable is Exclude<undefined | null, T>
function isEmpty(variable: any, allowEmptyString = false): boolean {
    return variable === null 
        || variable === undefined 
        || (variable === '' && !allowEmptyString);
}

笔记:

  • 使用===而不是== ;
  • 照顾undefined值;
  • 默认情况下(没有将参数allowEmptyString设置为true ),空字符串将被处理为undefinednull ,编译器将错误地认为它不是字符串。
  • Exclude参数是相反的,以便模拟布尔值上的“not”(它有效,但我不确定为什么)。

......或exists功能

但我建议使用exists函数以避免双重反转。 它更容易编写,更易于使用:

function exists(variable: string | null | undefined, allowEmptyString?: boolean): variable is string
function exists<T>(variable: T): variable is NonNullable<T>
function exists(variable: any, allowEmptyString = false): boolean {
    return variable !== null 
        && variable !== undefined 
        && (variable !== '' || allowEmptyString);
}

暂无
暂无

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

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