TypeScript无效的过载签名 - 与实现不兼容

时间:2016-04-15 16:34:10

标签: javascript typescript

我一直收到以下错误:

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有关。

1 个答案:

答案 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;