如何在TypeScript中将成员函数分配给变量?

时间:2014-05-07 08:53:07

标签: typescript functor

这是我正在尝试做的事情:

interface FunctionWithState {
    (): void;
    state: number;
}

var inc: FunctionWithState = {
    state: 0,
    apply: () => this.state++; // wrong syntax
};

基本上,我希望函数能够从外部维护某些状态。如何指定FunctionWithState类型的变量?

1 个答案:

答案 0 :(得分:1)

对于该特定行,您的半冒号错误。修复:

interface FunctionWithState {
    state: number;
}

var inc: FunctionWithState = {
    state: 0,
    apply: () => this.state++ // right syntax
};

但我怀疑您使用的是()=>错误。您希望它引用inc而不是全局变量this,在这种情况下是window

也许你的意思是使用一个类:

interface FunctionWithState {
    state: number;
}

class Inc implements FunctionWithState {
    state =  0;

    apply = () => this.state++;
};

var inc = new Inc();
inc.apply();

如果你真的想成为简单的javascripty,你可以做到以下几点。但是你不能调用apply函数(因为FunctionWithState上不存在):

interface FunctionWithState {
    (): void;
    state: number;
}

var tmp: any = function() { }
tmp.state = 0;
tmp.apply = function() { return this.state++; };
var inc: FunctionWithState = tmp;