dooglu
dooglu

Reputation: 281

How call callback in Typescript?

I have declared function:

 _translate(value: T, callback: (name: T) => T): void;

And function is:

public _translate(value: T, callback: T) {
    if (!this.translate) {
      callback(value);
    }
}

How to call(use) it? I tried the foLlowing:

this._translate(value, function(data: T) {
   console.log(data);
});

It does not work

Upvotes: 1

Views: 7113

Answers (2)

jcalz
jcalz

Reputation: 327934

You are not returning anything in your callback function, and you are not trying to use the result of your callback function from the caller... so, it looks like you should change the declaration of _translate to

_translate(value: T, callback: (name: T) => void): void;

That means the callback parameter should be a function which takes an input of type T and doesn't return anything (void). Then, you need to change the implementation signature to match:

public _translate(value: T, callback: (name: T) => void): void {
    if (!this.translate) {
      callback(value);
    }
}

and then you should be able to call _translate() as a method on an instance of your class, like:

// class with _translate() method is MapperServiceArray<T>
const thingy = new MapperServiceArray<string>(); 

// call _translate on the object with a string and a callback that 
// takes a string and does not return a value
thingy._translate("something", x => console.log(x.charAt(0)));

Now that I see your code snippet, I can suggest changes that make it compile (sort of), but I really don't know what you're trying to do. Hope that helped a bit. Good luck.

Upvotes: 5

S. Walker
S. Walker

Reputation: 2162

Try this:

// parameters: 
//   value, instance of T.
//   callback: function, accepting parameter (name) that is instance of T and returns object that is instance of T.
// returns: Void.
public _translate(value: T, callback: (name:T) => T): void {

}

and then to call it:

this._translate(value, (data: T): T => {
    return {};
});

Upvotes: 2

Related Questions