简体   繁体   中英

TypeScript with strictNullChecks and function to detect null values

Due to the nature of Javascript, I get myself checking if a value is != null && != '' all the time, so I created a function to check if values are empty, like this:

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

The problem is, other methods don't have a knowledge of what this means, so I have to use ! all the time to prevent warnings, for example:

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'
    }
};

My current solution is to do:

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

Is there a way to avoid using ! to prevent warnings?

Here is a solution:

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);
}

Notes:

  • Use === instead of == ;
  • Take care of undefined values;
  • By default (without a parameter allowEmptyString set to true ) an empty string is processed as undefined and null , and the compiler will mistakenly believe it is not a string.
  • Parameters of Exclude are reversed in order to simulate a "not" on the boolean value (it works but I'm unsure why).

… or an exists function

But I suggest an exists function in order to avoid the double inversion. It is easier to write, and easier to use:

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);
}

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