Javascript 打字稿重复函数实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39689763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:48:41  来源:igfitidea点击:

Typescript Duplicate Function Implementation

javascripttypescript

提问by James B

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

我在同一个 Typescript 类中定义了以下两个函数签名,即,

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?

如果函数签名中的参数数量不同,我认为您可以在打字稿中重载函数。鉴于上述签名分别有 2 个和 3 个参数,为什么我会收到此转译错误?

采纳答案by Mattias Buelens

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 implementationof a function, i.e. something like:

问题是你{}在前两行之后。这实际上定义了一个函数的空实现,例如:

function empty() {}

You only want to define a typefor 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
}