jeudi 23 avril 2015

Passing class method as parameter in Typescript

I'm searching for a possibility to pass a class-method to a function which then can execute that function on an instance of that class. Something like that pseudocode: (note that this is an abstract example)

class Foo {
    public somefunc() {
        // do some
    }
    public anyfunc() {
        // do any
    }
}

function bar(obj: Foo ,func: "Foo.method") {  // "that's what im looking for"
    obj.func();
}

bar(new foo(), Foo.somefunc);  // do some
bar(new foo(), Foo.anyfunc);  // do any

Is there a possiblity to do this?

I know i could be doing something like that:

class Foo {
    static somefunc(fooObj: Foo) {
        // do some
    }
    static anyfunc(fooObj: Foo) {
        // do any
    }
}

interface func {
    (fooObj: Foo);
}

function bar(obj: Foo, fn: func) {
    fn(obj);
}

bar(new foo(), Foo.somefunc);  // do some
bar(new foo(), Foo.anyfunc);  // do any

but that involves static functions which I don't want.

Aucun commentaire:

Enregistrer un commentaire