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?
TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.
The correct answer is THERE IS NO OVERLOADING IN JAVASCRIPT. Checking / Switching inside the function is not OVERLOADING. The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With