0

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;
}
2
  • 2
    Probably a typo? length Commented Nov 26, 2019 at 9:50
  • @saintlyzero sadly no, I just miss-typed here in the example. Commented Nov 26, 2019 at 10:13

4 Answers 4

2

First think type will be as following:

let foo: null | number | number[] = null;

// OR 

foo: number | number[];

Second, you need to use type guard to narrow down types to be able to reach the variable, i.e.

if(typeof foo === 'number') { 
  foo = 3;
}
else if (typeof foo === 'object' && Array.isArray(var)) {
  foo = [1,2,3];
}
else {
// whatever
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't quite like it but it's working out. Thank you.
1

you can check if it's an array through Array.isArray(foo) :

    if (Array.isArray(foo)){ 
     // array logic
    } else {
      // number logic
}

Comments

0

It is a typo change lenght to length

Comments

0

Try to check whether it is array and after you're sure that it is type of an array, then check its length:

if(Array.isArray(foo) && foo.length > 0) { 
    ... 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.