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.
Similar to JavaScript, to pass a function as a parameter in TypeScript, define a function expecting a parameter that will receive the callback function, then trigger the callback function inside the parent function.
And functions in Javascript are first-class citizens. Functions can be assigned to variables and functions can be passed as arguments to other functions. This makes it perfectly legal to pass a function to another function and then have that other function instantiate it with new .
An interface type cannot be passed as a parameter. When running TypeScript code, you are really compiling it down to JavaScript and then running the JavaScript. An interface is a TypeScript compile-time construct, so at runtime, there is no such thing as an interface type to call functions on or inspect properties of.
What are Callback Functions in TypeScript. A callback function is defined as a function passed into another function as an argument, which is then invoked inside the outer function to complete the desirable routine or action.
This doesn't compile-time check that the function came from a Foo
, but does the rest:
class Foo { public somefunc() { // do some } public anyfunc() { // do any } } function bar(obj: Foo ,func: () => void) { func.call(obj); } bar(new Foo(), Foo.prototype.somefunc); // do some bar(new Foo(), Foo.prototype.anyfunc); // do any
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