我一直收到以下错误:
error TS2394: Overload signature is not compatible with function implementation.
代码如下:
import Registry = require('../class/Registry');
type Format = Function;
type FormatRegistry = {
[s: string]: Format;
}
var registry = new Registry<Format>();
function formatAPI(): FormatRegistry; // get all formats // HERE GOES THE COMPILER ERROR
function formatAPI(name: string): Format; // get format
function formatAPI(name: string, format: Format): void; // register format
function formatAPI(formatMap: FormatRegistry): void; // register many formats
function formatAPI(nameOrMap?: string|FormatRegistry, callback?: Format): FormatRegistry|Format|void {
if (typeof nameOrMap === 'object') {
registry.registerMany(nameOrMap);
} else if (typeof nameOrMap === 'string') {
if (callback) {
registry.register(nameOrMap, callback);
} else {
return registry.get(nameOrMap);
}
} else {
return registry.list();
}
}
export = formatAPI;
我看不出上面的函数类型重载有什么问题。我试图逐个删除函数签名(和根据类型),但我失败了 - 我实现了一个空函数。
codeis背后的逻辑很好(所有测试都通过),只是重载在某种程度上是无效的。
此问题与this one有关。
答案 0 :(得分:0)
这在打字稿操场上对我来说没有任何错误:
class Registry<T> {
registerMany(items: FormatRegistry) { }
register(name: string, cb: Format) { }
get(name: string) { }
list() { }
}
type Format = Function;
type FormatRegistry = {
[s: string]: Format;
}
var registry = new Registry<Format>();
function formatAPI(): FormatRegistry; // get all formats // HERE GOES THE COMPILER ERROR
function formatAPI(name: string): Format; // get format
function formatAPI(name: string, format: Format): void; // register format
function formatAPI(formatMap: FormatRegistry): void; // register many formats
function formatAPI(nameOrMap?: string|FormatRegistry, callback?: Format): FormatRegistry|Format|void {
if (typeof nameOrMap === 'object') {
registry.registerMany(nameOrMap);
} else if (typeof nameOrMap === 'string') {
if (callback) {
registry.register(nameOrMap, callback);
} else {
return registry.get(nameOrMap);
}
} else {
return registry.list();
}
}
export = formatAPI;