February 1, 2018

TypeScript

Intention

The intention of this post is to sum up some thoughts on TypeScript that come from my own experience of working with it.

As with all engineering the right tool for the job is always dependent on the context of the job. The context where I would consider using TypeScript would be on projects that have a large codebase that will be developed and maintained by a large team of developers that have preliminary JavaScript or TypeScript knowledge. The advantages that come with using TypeScript will in my opinion outweigh the effort that has to spend on set up and the large amounts of boiler plate code that has to be written compared to using JavaScript. When setting up a proof of concept or a rather small project JavaScript will do just fine for my needs.

If you can afford however to invest in using something like Elm or ReasonMl I think this can definitely pay off. This because TypeScript does not do a good job at Polymorphism. Polymorphism is the provision of a single interface to entities of different types. It is a powerful mechanism that allows to treat different class instances through the same interface. The most well known form of polymorphism is probably runtime polymorphism. The canonical example for this form would be to calculate the surface area of shapes. In TypeScript this could be done like so:

Languages such as Haskell or C++ also offer ad hoc polymorphism or method overloading, meaning that the same function will act differently depending on the types of the arguments provided. The following example in C++ will yield for example in 2 times “Hello World”:

This is not possible in TypeScript, defining two methods with the same signature will compile to a JavaScript object with 2 times the same method definition. While the outputted code is valid JavaScript the behaviour will be that the latest defined method will always be invoked.

Hence to achieve simmilar behavior in TypeScript an interface function would have to be implemented that then dispatches function calls to the right method. Note that the same can be done with checking on datatype. It would be nice if TypeScript leveraged the type system more in order to allow to make use of ad hoc polymorphism and hence write better code.