2016-09-25 62 views
8

我已经在相同打字稿类中定义的以下两个函数签名,即打字稿复制功能实现

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

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

然而transpiling的打字稿我收到以下错误,当

error TS2393: Duplicate function implementation. 

我以为你可以重载函数在打字稿中提供数字在函数签名中的参数是不同的。鉴于上面的签名分别有2个和3个参数,为什么我会得到这个转译错误?

+0

在打字稿中没有重载函数,甚至没有泛型。 –

+2

请仔细阅读有关超载的文档。重载并不意味着你可以提供多个**实现**;这意味着你可以提供多个**签名**,只需一次执行。但在这种情况下,你为什么不简单地写'arg2?'? – 2016-09-25 17:46:18

+0

@torazaburo。我试图通过仿制药来确保类型安全。如果我使用'arg2',我仍然必须在'emit '中提供泛型类型'T2',尽管我可能实际上并不使用'T2'。我想我试图实现类似于C#的'Func'和'Action'委托签名。但是可能有更好的方法。 –

回答

10

我假设你的代码看起来是这样的:

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 
} 

的问题是,你第2行之后有{}。这实际上定义一个函数的空实现,即是这样的:

function empty() {} 

你只需要定义一个的功能,而不是一个实现。因此用空格替换空格:

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 
}