Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 591
xDreamCoding Avatar asked Apr 23 '15 11:04

xDreamCoding


People also ask

How do you pass a method as parameter in TypeScript?

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.

Can you pass a class as a parameter in JavaScript?

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 .

Can we pass interface as a parameter to a method in TypeScript?

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 is a callback function in TypeScript?

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.


1 Answers

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 
like image 100
Ryan Cavanaugh Avatar answered Sep 18 '22 11:09

Ryan Cavanaugh