Thursday, January 30, 2014

TypeScript and the ‘this’ keyword

One thing I was not aware of is that TypeScript will not automatically scope the this keyword to what you would expect. Only if you use the TypeScript arrow functions it will correctly set ‘this’ inside a function.

So the following code inside my TypeScript was wrong. In this code sample ‘this’ will refer to the caller object and not to the FormChangeTracker class as I would expect:

When I use the arrow function instead, this will be scoped correctly:

No comments: