Reputation: 3423
I am using Typescript for my function. I have two sets of data in the database, one is date
and one is time
. Both are expecting strings.
I made one POST
request when the user chooses the date, and that time will be selected for the user. I made a helper function for that, when the delivery time will start, it means user selecting time is expired, in which case I show them an alert on the front-end that shows.
"Your selected time expired!" .
I am trying to pass default date parameter like this now = new Date()
in my function instead of use directly new Date()
. When I console log typeof now
it shows the parameter is function.
PS: I am still new in Typescript. It will be great learning for me if someone give me detail about my mistake.
This is my function throws the error
const isStartimeExpired = (
date: string,
time: string,
now = new Date(),
) => {
const [startTime] = time.split(' - ');
const newDate = new Date(`${date}T${startTime}`);
if (newDate.getTime() < now.getTime()) { // this throws an error that getTime() is not function
return true;
} else if (isEmptyString(date) || isEmptyString(time)) {
return false;
}
return false;
};
This one works
const isStartimeExpired = (
date: string,
time: string,
) => {
const [startTime] = time.split(' - ');
const newDate = new Date(`${date}T${startTime}`);
if (newDate.getTime() < new Date().getTime()) { // this one does not throw any error
return true;
} else if (isEmptyString(date) || isEmptyString(time)) {
return false;
}
return false;
};
Upvotes: 0
Views: 230
Reputation: 170
You have to type the parameter now
into a date, else the type of the parameter is any
.
const isStartimeExpired = (
date: string,
time: string,
now: Date = new Date(),
) => {
const [startTime] = time.split(' - ');
const newDate = new Date(`${date}T${startTime}`);
if (newDate.getTime() < now.getTime()) {
return true;
} else if (isEmptyString(date) || isEmptyString(time)) {
return false;
}
return false;
};
Upvotes: 1