I want to create an function interface, that can act as a callable inside a class.
So basically what I want to do is the following:
interface Callable {
(x: number): number;
someAdditionalStuff?: any;
}
class Foo {
doSomething: Callable (x: number) {
return x + 3;
}
}
I know that Foo.doSomething hasn't the correct syntax.
I wondered if this is somehow possible to achieve?
Update: To make it little bit more clear. What I want is, that the type of doSomehting is Callable. But I want to flesh out the function body in the class, not in the interface and I don't want that you have to set someAdditionalStuff anywhere in the class or function implementation.
The target is, that I can add stuff to the class member, that are different, each time I create a new instance of the class.
You could write this:
interface Callable {
(x: number): number;
someAdditionalStuff?: any;
}
class Foo {
doSomething: Callable = (x: number) => {
return x + 3;
}
}
One important question is what you want the semantics of Foo.doSomething.someAdditionalStuff to be. With the above code, each instance of Foo gets its own copy of the doSomething closure, so changes in one class are not reflected in the other:
var x = new Foo();
var y = new Foo();
x.doSomething.someAdditionalStuff = 3;
// Changing this value does not change the value on 'x' - desired?
y.doSomething.someAdditionalStuff = 'foo';
I would guess this is what you want.
If you want someAdditionalStuff to essentially be 'static', there's a more complicated workaround that you could do. I'll try to come up with something simpler...
class _Bar {
someOtherThing() {}
doSomething(x: number) {
return x + 3;
}
}
interface Bar extends _Bar {
doSomething: Callable;
}
var Bar: { new(): Bar } = _Bar;
// User code:
var f = new Bar();
var g = new Bar();
f.doSomething.someAdditionalStuff = 'ok';
alert(g.doSomething.someAdditionalStuff); // "ok"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With