Before executing my code, I need to ensure that none of the variables in a given list are undefined.
In the code snippet below, there are 4 variables with uncertain values. While I can manually check variables a and b to satisfy TypeScript's requirements for number types, it becomes tedious when dealing with multiple variables.
Therefore, I attempted to create a function that could simultaneously verify the status of several variables at once. Unfortunately, this implementation resulted in a loss of type information, causing TypeScript to flag the code.
The script is executed with strictNullChecks
enabled.
let a = func1(),
b = func1(),
c = func1(),
d = func1();
function func1() {
return Math.random() === 0 ? 1 : undefined;
}
function func2(a: number, b: number) {
console.log(a);
console.log(b);
}
function anyUndef(a: any[]): boolean {
return a.filter(e => typeof e === 'undefined').length > 0;
}
if (typeof a !== 'undefined' && typeof b !== 'undefined') {
func2(a, b);
}
if (!anyUndef([c, d])) {
func2(c, d);
}