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

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

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

然而,当传输typescript时,我得到了以下错误

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 和 3 parameters respectively, why am I getting this transpilation error?

推荐答案

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

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
}

问题是前两行之后有{}个.这实际上定义了一个函数的empty implementation,例如:

function empty() {}

您只需要为函数定义type,而不是implementation.因此,用分号替换空块:

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
}

Typescript相关问答推荐

具有实体的ngrx SignalStore中的动态类型

使用类和子类以及迭代类属约束对类属递数据 struct 建模

如何在类型脚本中使用条件陈述循环

如何使用TypScript和react-hook-form在Next.js 14中创建通用表单组件?

如何将http上下文附加到angular中翻译模块发送的请求

为什么在TypScript中写入typeof someArray[number]有效?

无法绑定ngModel.条件ngSwitchCase中的错误

角效用函数的类型推断

在打印脚本中使用泛型扩展抽象类

将带点的对象键重新映射为具有保留值类型的嵌套对象

类型脚本可以推断哪个类型作为参数传递到联合类型中吗?

TypeScrip泛型类未提供预期的类型错误

下载量怎么会超过下载量?

React router 6(数据路由)使用数据重定向

根据类型脚本中的泛型属性 Select 类型

在打字应用程序中使用Zod和Reaction-Hook-Forms时显示中断打字时出错

在Thunk中间件中输入额外参数时Redux工具包的打字脚本错误

如何正确地将元组表格输入到对象数组实用函数(如ZIP)中,避免在TypeScrip 5.2.2中合并所有值

埃斯林特警告危险使用&as";

我的类型谓词函数不能像我预期的那样工作.需要帮助了解原因