使用扩展原型定义可调用的TypeScript函数

时间:2017-04-25 14:23:23

标签: javascript typescript interface

我想定义一个可调用函数foo()(不是类!我不想在这里使用new运算符),它也有一个属性foo.bar()。在简单的JS中,它将如下所示:

function foo() {
    // ...
}

foo.prototype.bar = function bar() {
    // ...
}

我在TypeScript中尝试使用如下界面:

interface IFoo {
    (): any;
    bar(): any;
}

const foo: IFoo = function(): any {
    // ...
};

foo.prototype.bar = function bar(): any {
    // ...
};

但是我收到了一个错误:

error TS2322: Type '() => any' is not assignable to type 'IFoo'.

似乎TS抱怨定义foo及其属性bar之间的中间状态,因为foo还没有属性bar,因此无法分配到const类型的IFoo。 我该如何解决这个问题?

以另一种方式提问:我如何为IFoo提供实施?

2 个答案:

答案 0 :(得分:0)

我找到了使用显式转换的解决方案

interface IFoo {
    (): any;
    bar(): any;
}

// explicit cast
const foo: IFoo = <IFoo>function(): any {
    // ...
};

foo.prototype.bar = function bar(): any {
    // ...
};

我不确定这是做到这一点的最好方法......

答案 1 :(得分:0)

如果您只想将foo作为类型注释,则可以执行以下操作:

const foo = function() {};
foo.prototype.bar = function bar() {};

type IFoo = typeof foo;
相关问题