My variable is declared with two possible types. Consider this example:
let foo: number | number[] = null;
Then, I have an if condition that assigns either a single number or an array to that variable:
if(condition) {
foo = 3;
} else {
foo = [1,2,3];
}
The issue arises when trying to perform actions on the variable while checking if it is an array.
if(!!foo.length) { ... }
This results in an error message:
Property 'length' does not exist on type number | number[].
I've read about user-defined type guards here: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards, but I couldn't get it to work. I also searched on SO without finding a solution.
To somewhat solve this, I resorted to hard-casting using as any
, although it's not the most elegant solution.
if(!!(foo as number[]).length) {
// This works if foo is an array
} else {
// This also works, allowing me to assign const a:number = foo;
}