Annoyance with TypeScript classes

I have to say I really enjoy using TypeScript! I’m a big fan of static typing and appreciate the confidence it gives me whilst refactoring. Plus the intellisense help is of course useful for exploring APIs.

It does suffer from downsides though. One of my bugbears is the complaints it gives when trying to dynamically add properties to objects with defined interfaces, which leads to messy and distracting casts to the default JavaScript anytype.

Another annoyance is the entire set of features related to TypeScript classes. It seems to me that the whole reason for their existence is to provide some familiarity for developers accustomed to the C-family of languages, e.g. c#, java, etc. to abstract away from prototypal inheritence.

The first problem I encountered is that the private modifier has no relevance to the resulting JavaScript. This is unfortunate because the classes are implemented via prototypal inheritance which doesn’t provide proper encapsulation. The reason this annoys me so much is that JavaScript already has encapsulation via variables declared within functions. This seems a step backwards for attempts to improve on an already flawed language. Especially as some in the developer community either don’t believe in encapsulation (comments include advocating writing an underscore before properties) or don’t believe that it exists in JavaScript.

Another problem is also related to the implementation via prototypes and it involves binding the value of this. We’re using knockout.js at my company to provide rich client side behaviour. Unwittingly I used an instance of a TypeScript class as a property of my view-model. The class, which referred to this stopped working due to knockout changing its value as part of the process of binding it to the view. Unfortunately as the unit tests were passing this was quite confusing!I believe the abstraction is leaky and will trip up more developers in the future. I’d recommend sticking to vanilla functions and building behaviour via composition rather than inheritance.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s