-2

I am trying to simplify checking if an index value is null or undefined in typescript.

    const indexValue: number;
    if(!!indexValue || indexValue === 0) {
     // Do something
    }

Since 0 is falsy, it seems like it needs to be explicitly checked for in the condition with indexValue === 0.

If there a more clear and concise way to do this?

nzpap
  • 7
  • It's either that or `indexValue === undefined || indexValue === null`. – jonrsharpe May 11 '21 at 16:28
  • 2
    "is truthy or 0", "is null or undefined", which one?! – ASDFGerte May 11 '21 at 16:28
  • 3
    `indexValue != null` – ray May 11 '21 at 16:29
  • 1
    What is `!!indexValue`? Why not `indexValue` ? – shahkalpesh May 11 '21 at 16:29
  • 1
    Note that `NaN` is falsy but is neither undefined nor null. You likely also want to reject `Infinity` and `-Infinity`. Consider instead `if (Number.isFinite(indexValue))`, which will reject non-numbers, null, undefined, NaN, and infinities. Perhaps clarify what you're going to use this number for, as the set of unacceptable values depends on that. – cdhowie May 11 '21 at 16:30
  • 1
    What's complex on `if (indexValue !== undefined && indexValue !== null) { ... }` o.O – Andreas May 11 '21 at 16:33
  • If it was that, i'd say [how-can-i-determine-if-a-variable-is-undefined-or-null](https://stackoverflow.com/questions/2647867/how-can-i-determine-if-a-variable-is-undefined-or-null), but the title says otherwise, so does the code. – ASDFGerte May 11 '21 at 16:38
  • @cdhowie The index is coming from an API will be used to get a value from a static array. I apologize for not being more descriptive but this is what I am looking for. I think `Number.IsInteger(indexValue)` would be better in my use case. Thanks. – nzpap May 11 '21 at 16:41

1 Answers1

0

Yes, there is. Since this is an index value, presumably you would like to accept any number. This could suggest that typeof indexValue === "number" is the right approach, since this will reject both null and undefined, but will accept 0. However, this condition will also accept other undesirable values, such as NaN, Infinity, and -Infinity, which are all numbers as well.

Thankfully, the language provides us with a bulit-in function that can test all of these at once: isFinite(). So your condition becomes:

if (isFinite(indexValue)) {
    // ...
}

Note that this function will accept strings that convert to finite numbers. There is also Number.isFinite(), which accepts only numbers, but is not supported in IE. If you want to reject all strings, then combine the isFinite() check with the typeof check:

if (typeof indexValue === "number" && isFinite(indexValue)) {
    // ...
}
cdhowie
  • 158,093
  • 24
  • 286
  • 300