I normally like my Javascript like my ice cream: plain and Vanilla, but that doesn’t mean I am not open to new flavors, TypeScript seems to be one of those new Javascript flavors, “Javascript that scales” as they promise. So come along and follow me as I try to figure out this new thing.
On a first quick pass, TypeScript introduces Type Annotations, handy definitions for variables:
function(**arg: string**){
//use string argument }
The above bit of code should throw a warning when not receiving a string as an argument.
The first gotcha, is the following example:
See the Pen TypeScript 001 by Eugenio Keno Leon (@k3no) on CodePen.
TypeScript is a superset of Javascript, which means that whatever runs in Typescript will probably also run in Javascript, in order to see a warning about an incorrect type, we would need a different setup so…
I am going with Atom (Cause it’s free and awesome).
Start by installing Atom-Typescript
You will now be able to make .ts - Typescript files and Atom will warn you when your types are wrong:
See the Pen TypeScript - Types by Eugenio Keno Leon (@k3no) on CodePen.
Typescript also brings Interfaces to Javascript (see Note)so…
See the Pen TypeScript - Interfaces by Eugenio Keno Leon (@k3no) on CodePen.
So we have a basic interface and a function that implements it, to see it fail and why it is useful, we need to go back to our desktop editor and try to compile our typescript file, you will get the following error if you ommit part of the interface:
Besides Interfaces and Types, Typescript adds Classes to Javascript, which you might already be using if you do ES6 ( See note ) and code sample.
See the Pen TypeScript - Classes by Eugenio Keno Leon (@k3no) on CodePen.
And breaking our new class is just a matter of ommiting a variable..
Like in Javascript’s es6, Typescript provides some extra handy features to the Class syntax, let’s explore.
Extending Classes
See the Pen TypeScript - Class Inheritance by Eugenio Keno Leon (@k3no) on CodePen.
Class Modifiers: Public & Private
See the Pen TypeScript - Class Modifiers by Eugenio Keno Leon (@k3no) on CodePen.
So while this example still compiles an runs, in your editor you would get errors:
There are quite a few other things that Typescript adds to Javascript, I’ll try covering the rest on a second post, you can also check the full feature set from them, but for now I leave fairly impressed on how easy it is to get into Typescript.
Best,
Keno