user11104582
user11104582

Reputation:

"Expected 0 arguments, but got 2" with TypeScript overloading

I have a class with an overloaded method (two versions).

One version takes no arguments. The second can take two.

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 call this.getEndDateTime("8/11/2019, 11:42:17 PM", 5), TypeScript gives me an error, "Expected 0 arguments, but got 2." How do I satisfy TypeScript here?

I'm running Node v10.16.0, using TypeScript v3.5.2. I've tried switching the order of the overloads:

// Switch the order
...
    getEndDatetime(startTime?: string, duration?: number): string;
    getEndDatetime(): string { 
        ...
    }
...

TypeScript then highlights startTime and duration within the code, saying it can't find it.

I expected my first overload implementation to not throw any errors when called with two parameters, but it does.

Reading from elsewhere suggest my code should pass.

Upvotes: 6

Views: 6129

Answers (1)

Justin Collins
Justin Collins

Reputation: 350

It is likely because the transpiler is unable to determine which method you are wanting to call due to the two parameters signature being optional. In other words getEndDateTime() could refer to either signature you defined. To support this, you'll want to make startTime and duration no longer optional.

getEndDatetime(): string; 
getEndDatetime(startTime: string, duration: number): 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();
    }
}

Upvotes: 3

Related Questions