Reputation: 4760
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?
Upvotes: 5
Views: 1228
Reputation: 23752
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:
===
instead of ==
;undefined
values;allowEmptyString
set to true
) an empty string is processed as undefined
and null
, and the compiler will mistakenly believe it is not a string.Exclude
are reversed in order to simulate a "not" on the boolean value (it works but I'm unsure why).exists
functionBut 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);
}
Upvotes: 6