2

I have a class with an optional field startDateHour:

export class Test {
  startDateHour?: number;

  // more fields, constructor etc.
}

I want to do something, if startDateHour exists:

if (test.startDateHour) {
  //do something
}

The problem is that this check doesnt work as expected when startDateHour is 0. If its 0 it still exists and i want to execute the code, but if (startDateHour) returns false in that case.

Of course i could do something like:

if (test.startDateHour || test.startDateHour === 0) {
  // do something
}

But is there a better way, like one check which does both the things above?

M.Dietz
  • 900
  • 10
  • 29
  • `test.hasOwnProperty("startDateHour")`, `"startDateHour" in test`, `test.startDateHour == undefined`, `typeof test.startDateHour == "undefined"`. Take your pick. – VLAZ Dec 06 '19 at 13:00
  • at any time 0 is false.. – Surya Prakash Tumma Dec 06 '19 at 13:00
  • `if (!isNaN(test.startDateHour))` is also an option – bugs Dec 06 '19 at 13:01
  • This is JS basics Falsy, Truthy - https://developer.mozilla.org/en-US/docs/Glossary/Falsy – Maciej Sikora Dec 06 '19 at 13:01
  • What you could do, is write a utility method, that checks for not `null` and not `undefined` and can be used like: `if(isAssigned(test.startDateHour))` – r3dst0rm Dec 06 '19 at 13:01
  • @r3dst0rm or avoid the utility method and just do `val == null` or `val == undefined` - in both cases, you're checking for *both* of these. It's a slight "hack" with loose equality but it's probably the best use of it. – VLAZ Dec 06 '19 at 13:03
  • 1
    Does this answer your question? [How do I check if an object has a specific property in JavaScript?](https://stackoverflow.com/questions/135448/how-do-i-check-if-an-object-has-a-specific-property-in-javascript) – VLAZ Dec 06 '19 at 13:05
  • Simple `if(!test1.startDateHour) {}` does the trick as `undefined`, `null` and `0` all equate to `false` and anything else as true. – Bargros Dec 06 '19 at 14:20

2 Answers2

2

0 is falsy. But the latest typescript version provides another operator called Nullish Coalescing. Depending on what you want to do within the if you might want to use that.

Read about it here for example: https://dev.to/obinnaogbonnajoseph/optional-chaining-and-nullish-coalescing-typescript-3-7-5899

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
  • Nice information. Allthough, how would it look then: `if (test.startDateHour ?? undefined !== undefined) { /* something */ }` ? – David Renner Dec 06 '19 at 13:27
  • You wouldn't use the operator within the if-condition. That's why I said depends on what he wants to do within the if statement. `0 ?? 1 returns 0`, while `0 || 1 returns 1` – MoxxiManagarm Dec 06 '19 at 13:29
0

Try this,

if(!isNaN(test.startDateHour)) {
}
Gangadhar Gandi
  • 2,162
  • 12
  • 19