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?
0andfalsestrictNullChecksto true in your tsconfig.json file.