TypeScript, Angular and Factories - Another Gotcha (Classic Functions vs Arrow Function)

Wednesday, August 5, 2015

In my last post I talked about how AngularJs Factories need to be instantiated first before they are returned to the calling code.

I came across another problem while converting my JavaScript Angular code to TypeScript and that is how public functions are created in JavaScript depending on how you structure them in TypeScript.

Consider the following TypeScript code:

Which then generates this JavaScript code:

The problem here is the code that is generated builds a function by creating a prototype and the way this code is structured, "this" is referring to the global lexical scope and not scope of this class. So this.$http is undefined.

Funny thing is I did not originally write the code this way but using Visual Studio and Resharper, the code suggestion asked me if I wanted to change it.  Hey! Why not?? Looks cleaner.

Here is the slightly different TypeScript example, this time using arrow function to implement the needed function:

And again, here is the generated JavaScript

Now the generated getUser function is in my constructor as a closure function and the "this" has been preserved by defining it with the "_this" variable. Plus, I think this approach is easier to read.

I think the point here is that in TypeScript, you should try as much as possible to opt for the arrow functions. As matter of fact, if you go the TypeScript Handbook site, they talk about this in detail.

comments powered by Disqus