Pregunta

Here's what I’m trying to do:

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

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

Basically, I want the function to maintain some state accessible from outside. How can I assign a variable of the type FunctionWithState?

¿Fue útil?

Solución

For that specific line, you have a wrong semi colon. Fix :

interface FunctionWithState {
    state: number;
}

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

However I suspect you are using ()=> wrong. You want it to refer to inc and not the global variable this which is window in this case.

Perhaps you mean to use a class :

interface FunctionWithState {
    state: number;
}

class Inc implements FunctionWithState {
    state =  0;

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

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

If you really want to be plain javascripty about it you can do the following. But then you cannot call the apply function (as it does not exist on FunctionWithState):

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

var tmp: any = function() { }
tmp.state = 0;
tmp.apply = function() { return this.state++; };
var inc: FunctionWithState = tmp; 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top