Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: isNaN not accepting Date Object

Tags:

typescript

const isObjectClass = (value: any, className: any) => (Object.prototype.toString.call(value) === `[object ${className}]`);

export const isDate = (value: any) => isObjectClass(value, 'Date');


const time = (time: Date): string => {
    return ((isDate(time) && !isNaN(time)) ? time : new Date()).toISOString();
};

In the above function time, I am checking if the input is a valid Date object or not. If valid, it will return the string version of passed Date. If invalid, it will return the string version of the current date.

The problem with isDate() is, it will return true for input values new Date() and new Date(undefined)). To avoid this I used !isNaN() which return false in case of !isNaN( new Date(undefined) ).

Now the problem is typescript is not allowing me to pass Date object to isNaN function.

error

TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.

Any suggestions?

like image 217
lch Avatar asked Jun 27 '26 02:06

lch


1 Answers

You can convert this date object to time (!isNaN(time.getTime())) like as follows,

const time = (time: Date): string => {
return ((isDate(time) && !isNaN(time.getTime())) ? time : new Date()).toISOString();
};

In here getTime method returns numeric value of the respective date object. So you can easily use this numeric value with isNaN

like image 110
Kural Avatar answered Jun 28 '26 15:06

Kural



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!