打字稿重复功能实现

Jam*_*s B 24 javascript typescript

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

public emit<T1>(event: string, arg1: T1): void {}
Run Code Online (Sandbox Code Playgroud)

public emit<T1,T2>(event: string, arg1: T1, arg2: T2): void {}
Run Code Online (Sandbox Code Playgroud)

但是,当转换打字稿时,我得到以下错误

error TS2393: Duplicate function implementation.
Run Code Online (Sandbox Code Playgroud)

我认为你可以在typescript中重载函数,只要函数签名中的参数数量不同.鉴于上述签名分别有2个和3个参数,为什么我会得到这个转换错误?

Mat*_*ens 21

我假设您的代码如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

问题是你有{}前两行.这实际上定义了一个函数的空实现,即:

function empty() {}
Run Code Online (Sandbox Code Playgroud)

您只想为函数定义类型,而不是实现.所以用一个分号替换空块:

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
}
Run Code Online (Sandbox Code Playgroud)

  • 当您在 TypeScript 中重载时,您只有一个具有多个签名的实现。见 /sf/ask/924883781/ (7认同)
  • 那么,如果这三个函数包含不同的逻辑呢? (2认同)

Eng*_*hly 16

因为您在同一窗口中打开 Typescript 和 JavaScript 文件,所以IDE可以通过三种方式解决此问题:

第一个解决方案:

仅打开 typescript 文件或仅打开 JavaScript 文件

第二种解决方案- 运行以下命令:

tsc--init

tsconfig.json该命令将为打字稿配置创建文件

最后解决方案

出口{}

在文件的顶部


小智 14

export {}
Run Code Online (Sandbox Code Playgroud)

只需在打字稿文件的顶部添加这一行

  • 有用。问题是:为什么?:-) (4认同)