简体   繁体   中英

How to pass no value to Date object using TypeScript null check

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM