簡體   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