Typescript Duplicate Function Implementation

JavascriptTypescript

Javascript Problem Overview


I have defined the following two function signatures in the same Typescript class, i.e.,

public emit<T1>(event: string, arg1: T1): void {}

and

public emit<T1,T2>(event: string, arg1: T1, arg2: T2): void {}

However when transpiling the typescript I get the following error

error TS2393: Duplicate function implementation.

I thought you could overload functions in typescript providing the number of parameters in the function signature were different. Given that the above signatures have 2 and 3 parameters respectively, why am I getting this transpilation error?

Javascript Solutions


Solution 1 - Javascript

I'm assuming your code looks like this:

public emit<T1>(event: string, arg1: T1): void {}
public emit<T1,T2>(event: string, arg1: T1, arg2: T2): void {}
public emit(event: string, ...args: any[]): void {
    // actual implementation here
}

The problem is that you have {} after the first 2 lines. This actually defines an empty implementation of a function, i.e. something like:

function empty() {}

You only want to define a type for the function, not an implementation. So replace the empty blocks with just a semi-colon:

public emit<T1>(event: string, arg1: T1): void;
public emit<T1,T2>(event: string, arg1: T1, arg2: T2): void;
public emit(event: string, ...args: any[]): void {
    // actual implementation here
}

Solution 2 - Javascript

export {}

Just add this line at the top of the typescript file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames BView Question on Stackoverflow
Solution 1 - JavascriptMattias BuelensView Answer on Stackoverflow
Solution 2 - JavascriptCoders_ GroundView Answer on Stackoverflow