4

I'm just getting started with Angular 2 and TypeScript and I can't seem to figure out how to use callback functions, I know this may be a silly question but given this regular javascript code:

someOnject.doSomething('dsadsaks', function(data){
      console.log(data);
});

What is the equivalent in TypeScript?

2 Answers 2

6

The same code works in TypeScript. Alternatively you can use

someOnject.doSomething('dsadsaks', data => {
  console.log(data);
});

The difference is that in the 2nd version this. would refer to the class surrounding the code.

Sign up to request clarification or add additional context in comments.

4 Comments

hey you mean if this will refer to class variable or function variable ??
@NaumanAhmad sorry, I don't understand what you mean. this refers to the class. I'm not dure myself what I referred to with this sentence ;
thanks i was just asking if this when used in above callback function will it refer to class or call back function ?
To the class. .
4

Your example is perfectly valid in a TypeScript project. If you wanted you could also strongly type your inputs:

const msg:string = 'dsadsaks'
someOnject.doSomething(msg, data:string =>{
      console.log(data);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.