I have a variable that's declared as two types. Let's take as example this:
let foo: number | number[] = null;
After that I have an if condition that assign a single number or an array to that variable:
if(condition) {
foo = 3;
} else {
foo = [1,2,3];
}
The problem starts here. I can't do any action on that variable if I need to check it like if it is an array.
if(!!foo.length) { ... }
This gives me an error:
Property 'length' doesn't exists in a type number | number [].
I've red this topic: https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards but I was not able to make it works. I've also searched here on SO without finding anything that could have helped me.
I've kinda solved hard-casting it as any and it works, but is not an elegant solution.
What am I missing?
if(!!(foo as number[]).length) {
// this works if foo is an array
} else {
// this works too and I can just do something like const a:number = foo;
}
length