Typescript: A soft requirement for Ionic 2 / Angular 2

This isn’t a tutorial on how to setup and get started on Typescript, just some snags I ran into, my early ups and downs with the framework, as well as my honest assessment.

Angular & Typescript: The perfect partnership

Angular 2 is a complete overhaul of the Angular framework. It uses some of the big bold ideas of ECMAScript 6 (2015) to set its platform, but even that isn’t enough to standardize certain aspects of the ever-sloppy Javascript language. One of those big, sloppy topics is the lack of typing. The ability to be expressive in Javascript ranges beyond any other programming language, which best describes its blessing (yay for endless patterns) and its curse (maintainability doesn’t exist).

Enter Typescript! Microsoft is infamous for creating some web tool blunders. The last time I remember them having a hand in Javascript was their attempt at creating their own; who remembers JScript? Most of us blocked it out. The good news is, under the new lead of Satya Nadella Microsoft has been seemingly making several right decisions, and thus far, it seems like Typescript is one of them. Angular 2 was the perfect vessel to bring Typescript to the foreground, I’m not sure how anyone would have recognized it otherwise.

Typescript isn’t required to write Angular 2, but I highly recommend it

Since Angular teamed up to get the best out of TS, and the learning curve is so minimal to get on board, it is certainly worth it to go ahead and learn while learning Angular/Ionic. It certainly isn’t required to plain ole’ Javascript, but as easy is it is to bring into a project, it is worth seeing if it is for you.

Typescript: Tips to avoid frustration

When a constructor’s parameter is set to private, that variable is automatically scoped to that class. This saves you a little typing, but it’s not that big of a deal, it’s just one of the quirks you need to accept and get used to.

Constructor parameters set to private are auto-scoped
to the class
class MyApp { private privNum: number; public pubNum: number; constructor (private someNumber: number, private _ajaxService: AjaxService) {
//These private vars brought in as parameters don't need to be declared, they already are
this.someNumber = someNumber; this._ajaxService = _ajaxService;
//If you want any of the MyApp's class vars to be set, do that here
this.privNum = 10; this.pubNum = this.privNum * 10; } }

This is more ECMAScript6/2015 knowledge. When using multiple parameters in a fat arrow => function, you need to wrap the parameters with ()’s or you will get the following error: The left-hand side of an arithmetic operation must be of type ‘any’, ‘number’ or an enum type. Cannot find name ‘a’ (was parameter) although just one parameter doesn’t require ()’s.

Parentheses required for more than one fat arrow parameter
const arr = [9,3,3,2]; let arrAvg = arr.reduce(a, b => a) / arr.length;
//This is missing parentheses around the a,b parameters, and will throw an error in JS (or TS compiler)
let arrAvg = arr.reduce((a, b) => a) / arr.length;
//Add () and you are all good
let arrNum = arr.reduce(a => a);
//Or having just one parameter doesn't require ()'s

When you need to use an interface but don’t have an instance of the interface’s object (new ICoolClass()) you can still cast the object..

Using an interface w/out instance of object
const newCoolClass = <ICoolClass>{};
//The newCoolClass has all of the available properties that the interface does.

And then there are some more complex, funky things that you have to do in order to get around strict typing, that may be annoying since this whole concept is knew to us JS developers.
In this example, since the creator of querySelectorAll decided to make the method return a NodeList (rather than a simple array or HTMLCollection), hence it requires a little adjustment to get a simple thing like iterating over the results of a selection.

Pro tip: A quick way to get an element’s type in the CDT console, is to select the element and do a element.constructor.name so const lis = document.querySelectorAll('li'); console.log(lis.constructor.name);

Cast querySelector to a specific array in order to iterate over it
let editableArea = document.querySelectorAll('[contentEditable]'); editableArea.forEach((editArea) => return true);
//This will error and not compile in TS
let editableArea = document.querySelectorAll('[contentEditable]'); editableArea.forEach((editArea) => return true);

The only other tips I would say to consider is to have a smart IDE such as IntelliJ (or their sub-packages), or even the newly free Visual Studio, which is super fast and has great speeds (remember me saying MS is doing good things?). A good IDE will cover code completion and compile Typescript properly to get you on your way to some rapid app development.

General Consensus

…is that Typescript is good. The little bit of extra work that you do solves a lot of problems that front-end/Javascript teams often run into:

  • Incompatible type errors: Obviously the big one, and this could mostly sum up all of the problems. Strings shouldn’t be numbers and numbers shouldn’t be booleans, but they are in Javascript. Typing each variable solves this problem.
  • Incorrect function parameters: Typescript allows you to type nearly everything, including the parameters you expect to get in a function call. Now if a coworker isn’t so good at connecting a variable’s name and its expected use, such as the variable showSection that expects the string “yes”/”no” rather than true/false boolean, this can now be solved by adding the showSection:boolean type restriction.
  • Maintainability is achievable: With only the two small examples above you can see how having expected variable/object/function types can help a team understand functions faster (especially the un-commented ones). With modern IDE’s and their sexy code completion (I use IntelliJ / Web Storm) code completion is working overtime and helping you to write code faster, alerting you when there is an type incompatibility.

Coming up next, my humble update on Ionic 2 and Angular 2

Stay tuned!

Leave a Reply