3

给定接口

interface FooWithBar {
    ():void;
    bar():void;
}

我如何编写实现?

function foo(){

}
foo.bar = function(){

};

不起作用,因为它会引发错误,“类型'() => void 上不存在属性'bar'”。但是,如果我声明的类型fooFooWithBar

```` var foo: FooWithBar = function () {

};
foo.bar = function () {

};

````

我收到另一个错误,“类型'() => void'不可分配给类型'FooWithBar'。类型'() => void'中缺少属性'bar'”。

我该如何解决这个catch-22?

4

2 回答 2

2
function FooWithBar() {
  // ...
}
module FooWithBar { // n.b. can use 'namespace' keyword here instead of 'module' if you like
  export function bar() {
    // ...
  }
}

这是一些避免出现在“仅代码答案”审查队列中的文本。

于 2015-10-30T22:11:02.063 回答
1

有几种方法可以解决这个问题:

假设界面如下:

interface FooWithBar
{
    ():void;
    bar():void;
}

命名空间导出

function FooWithBar(){

}
namespace FooWithBar{
    export function bar(){

    }
}

铸件

let foo:FooWithBar = function(){

} as FooWithBar;
foo.bar = function(){

};

namespace关键字不能用在函数体中,所以如果需要工厂foo,请使用第二种方法。

于 2015-11-02T17:24:22.123 回答