I am facing an issue with a class containing an overloaded method that has two versions.
One version does not take any arguments, while the second one can take two arguments.
class DFD {
...
getEndDatetime(): string;
getEndDatetime(startTime?: string, duration?: number): string {
if (!startTime || !duration) {
return new Date(this.getEndDatetimePOSIX()).toLocaleString();
} else {
this.getEndDatetimePOSIX(startTime, duration);
return new Date(this.getEndDatetimePOSIX(startTime, duration)).toLocaleString();
}
}
...
}
When I make a call to
this.getEndDateTime("8/11/2019, 11:42:17 PM", 5)
, TypeScript returns an error stating, "Expected 0 arguments, but got 2."
How can I resolve this issue in TypeScript?
I am using Node v10.16.0 and TypeScript v3.5.2. I attempted to switch the order of the overloads:
// Switch the order
...
getEndDatetime(startTime?: string, duration?: number): string;
getEndDatetime(): string {
...
}
...
TypeScript then raises an error indicating that it cannot find startTime
and duration
within the code.
I expected my first overload implementation to work without errors when called with two parameters, but unfortunately, it is still throwing errors.
References and help from other sources suggest that my code should be correct.