Typescript? Hands on in 5 mins.

Google Trend of Typescript

TL;DR

Getting started with Typescript in 5 mins. Toy chat project with Gulp and Firebase provided to get things moving. Get the source here.


Typescript?

I first heard about Typescript from the announcement that Angular 2 will be built with Typescript. And Angular team’s effort on AtScript will be merged into Typescript 1.5+.

I am not going to debate whether typed Javascript is necessary, but there has been some momentum on type-check or typed languages transpiling to Javascript.

The rest of this post will focus on getting a Typescript project started, so you can experiment and see how your Typescript code transpiles into Javascript.


Javascript library => Typescript => Javascript

You can code in Typescript, then use it on the client side or the server side as Javascript. There are two extra steps to the normal workflow.

  1. Transpiling your code into Javascript
  2. Import definitions of Javascript library

Transpiling Typescript code => Javascript code is taken cared of by gulp-typescript. You can also setup Webstorm to transpile you code on the fly.

What about leveraging existing Javascript code in Typescript? The DefinitelyTyped project is a repository hosting type definitions of various Javascript library packages.

To install the definition files, use tsd. The tool is very similar to bower and npm.

Note that tsd only installs the type definition (.d.ts) and you’ll still need to install the Javascript library through bower or npm.


Let’s build something fun!

We are ready to start coding! Let’s build a simple chat using Firebase.

Line 1 imports the firebase type definition installed using tsd. If you look into the definition file, you’ll find the definition of Firebase.

When we try to create Firebase instance in Line 13, the Typescript transpiler makes sure firebaseURL is string. Otherwise, it would generate an error.

You may notice that we haven’t specify the type of firebase in Line 9. Turns out the transpiler performs type inference for you. Try the code out in Webstorm, and you’ll get code completion and all the type check goodies.

The code is fairly straight forward as most of the heavy lifting is handled by the Firebase library.


Let me play with it!

To play with it, clone from github and check out the intro tag. Load up index.html file in your Google Chrome browser, open up Developer Tools and voila!

Questions and feedbacks are welcome!

References

  1. Gulp tasks are taken from https://github.com/DanWahlin/AngularIn20TypeScript/blob/master/gulpfile.js
  2. Typescript Introduction — http://www.typescriptlang.org/Handbook
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.