1

I am looking way to do something like

value ? new Date(value) : new Date()

using TypeScript null check

new Date(value ?? xxx)

It is even possible?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Edgaras Karka
  • 7,400
  • 15
  • 61
  • 115

1 Answers1

4

Use Date.now():

new Date(value ?? Date.now())

Note that value should be a number in this case. If it is a string, you'll need to use:

new Date(value ?? new Date(Date.now()).toISOString())`

at which point you're better off with the original code, in my opinion. That said, be aware of the problems with depending on date parsing using the Date constructor, outlined in Why does Date.parse give incorrect results?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122