Friday, January 31, 2014

Interfacing Scope in TypeScript

TypeScript at its heart is a type inference engine. And that is what makes it beautiful. But JavaScript is so freaking flexible that it is hard to infer too much. Note that C# has type inference but it is bound within a method. Also since JavaScript is untyped you don't really have much type information to start off with. So the solution is to have programmers add type information and that will allow TypeScript to do type inference and theoretically detect errors.

So one key aspect of Angular is the creation of "scope". This scope acts as the glue between the model and view and is set up by the controllers. Working on this scope allows the automatic data binding to happen. The project I based my Angular and TypeScript project on initially (a project done across the hall by another team) had an interface defining the scope. So I am assuming the thought was that everything should have a type like in a strongly typed language (like C# or Java), but is this valid?

The scope object is used in exactly two places. Using it outside those places is almost guaranteed to be a mistake. These places are the controller and the html partial that maps to that controller. Inside the partial the tools do not help you with error checking or intellisense. So the scope is just used inside one function so having an interface for it seems to buy you very little, but it does require you to constantly update the scope interface. Also the scope interface will not be accurate because the HTML partial is capable of creating values of the scope which will not need to be reflected in your scope object.

For this reason, we have decided not to place interfaces on scope objects as this does not buy us the power of typing and limits our flexibility. Typing is a powerful tool in programming, but it is not universally good in all situations. Even strongly typed languages like C# and Java have made allowances for more dynamic typing.


No comments:

Post a Comment