Say Hello to TypeScript

What is TypeScript?

TypeScript is a free and open source programming language that was developed by Microsoft. It is a superset of JavaScript, and essentially adds optional static typing and class-based object oriented programming to the language. Every JavaScript program is also a TypeScript program. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. For a large Javascript project, adopting TypeScript can result in more robust software while still being deployable where a regular JavaScript application can run.

Are there other technologies like it?

There's CoffeeScript, but that serves a different purpose. CoffeeScript makes a lot of changes to JavaScript's syntax and uses JavaScript's object-oriented capabilities in a particular way, but doesn't fundamentally alter the way the language works.

There's also Dart from Google, but that's a full on replacement for Javascript. Dart's goals aren't identical to TypeScript's. Google thinks that some of the semantics of JavaScript are fundamentally problematic, so Dart changes these semantics. However, both Dart and TypeScript are designed to aid in large-scale application development using module systems and optional static type checking as the fundamental tools to support that, and both can be compiled to JavaScript.

Tooling and IDEs

Node.js

The command-line TypeScript compiler can be installed as a Node.js package. To do that, first run Node.js and run:

npm install -g typescript

Then you can compile TypeScript files with a command:

tsc filename.ts

Visual Studio

Visual Studio 2012 developers can install the TypeScript editor plugin to get rich TypeScript tooling inside Visual Studio. It is recommended to install the Web Essentials extension to get full support for TypeScript preview and compilation. ReSharper 8 from JetBrains is going to support TypeScript, too.

PhpStorm/WebStorm

WebStorm/PhpStorm from version 6 introduces full support for the TypeScript language through the new Source Maps feature. I am going to talk about Source Maps a little bit later.

Quick example

In the example below we have a piece of code in the TypeScript. It contains two classes: Person and Main. The first one has a constructor with an optional name parameter and a public method getName(). The other class Main uses a Person class and initiates two instances of it. Pay attention to the static Person.defaultName member, which is used if Person’s constructor is named without a name parameter.

Photo 1
A typeScript code converted to a JavaScript code looks like this:
Photo 2

At the end of the generated file we see a //@ sourceMappingURL=Person.js.map comment. I will explain it a bit later.

Let’s dig deeper

module and class

JavaScript practice has at least two common design patterns: the module pattern and the class pattern. Roughly speaking, the module pattern uses closures to hide names and to encapsulate private data, while the class pattern uses prototype chains to implement many variations on object-oriented inheritance mechanisms.

Namespaces are introduced using the module keyword. By default, the internal stuff in a module is not made visible outside of the module. To make it visible we have to use the export keyword.

Photo 3

Now we can access class Person from outside the module via a fully qualified name

DevBridge.Blog.Examples.TypeScript.Person.

Reference and Import

To access stuff in a remote TypeScript file, we first need to add a reference to it. The second thing we can do is to add an import statement to import internal or external modules and create local aliases by which they may be referenced:

import Identifier = ModuleReference;
Photo 4

Types

TypeScript adds optional static types to JavaScript. Types are used to place static constraints on program entities such as functions, variables, and properties so that compilers and development tools can offer better verification and assistance during software development.

any

The any type is used to represent any JavaScript value. If we don’t specify a type for member or function its type is resolved as any type:

Photo 5

 

 

 

number, bool, string, null, undefined

The primitive types are the Number, Boolean, String, Null, and Undefined types. Let the code speak:

Photo 6

void

The void type, referenced by the void keyword, is used as the return type for functions that return no value. The only place the Void type may appear is in a return type annotation for a function.

interface

Interfaces have no run-time representation in JavaScript. They are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions.

Photo 7

implements and extends

Class inheritance, as you are probably familiar with it, is not something you’d want to hand code in JavaScript. This is an area where TypeScript clearly shines brightly. In the example above, we already used the implements statement to implement the IPerson interface for the class Person. Now lets inherit a Person class in the Student class:

Photo 8

You should use a super keyword in the constructor of a derived class to pass parameters to the base class constructor. Super calls for passing parameters are not allowed outside the constructor in TypeScript, though you can use super keyword to invoke methods of the base class from the derived class.

private or public

Members have either public or private accessibility. The default is public accessibility, but member declarations may include a public or private modifier to explicitly specify the desired accessibility.

properties

Below you will notice that there are two methods named Name. Notice the “get” and “set” in front of the methods. TypeScript Getters and Setters are called TypeScript Accessor.

Photo 10

default values

In TypeScript you can specify a default value for the constructor or method members:

Photo 11

arrow function () => { }

TypeScript supports arrow function expressions, a new feature planned for ECMAScript 6. Arrow function expressions are a compact form of function expressions that omit the function keyword and have lexical scoping of this.

Photo 12

It’s time to DEBUG

Debugging with Visual Studio and Internet Explorer

If you run a TypeScript enforced application with Internet Explorer, Visual Studio can do debugging right inside Visual Studio.

Photo 13

Debugging with other browsers

Have you heard of Source Maps? Source Maps is an idea that has come out of Mozilla for addressing the debugging issues that are raised by *-to-JavaScript compilers and JavaScript minifiers, the problem is that when you use these you ultimately aren't debugging what you wrote.

Lets enable the Source Maps option for Goolge Chrome developer tools:

Photo 14

Now you need to enable the Source Map generation from the TypeScript file. First you need to compile the .ts file with the -sourcemap flag in order to generate a source map file. 

In Visual Studio you need to go to Options → Web Essentials → TypeScript and set the Generate Source Map option to True.

Photo 15

Now you'll have two files generated from .ts file, generatedfile.js and generatedfile.js.map. The JavaScript file will also contain the source map pointer:

Photo 16
 
 
 

Now lets try to debug TypeScript in a Google Chrome browser. First, look at Sources - you should see your .ts file listen with .js files. Select your .ts file and add a breakpoint. Now refresh the page - your browser should hit the breakpoint:

Photo 17

As you can see - we have a regular debugging experience here!

Conclusions

TypeScript offers classes, modules, and interfaces to help you build robust components. These features are available at development time and provide developers with the confidence that it will not break, but are compiled into simple JavaScript. This was a missing piece of JavaScript, which is fulfilled by TypeScript.

And one more thing...

The community has started collecting TypeScript type definitions for popular JavaScript libraries. These files (ending in .d.ts) describe the public api of an existing library, just like .h files do for C code. This allows you to write TypeScript code against JavaScript libraries without them having to change anything.

Useful Links

TypeScript - Official Website

TypeScript Language Specification

Definition files -  DefinitelyTyped project on GitHub

Installing TypeScript on a Mac

TypeScript: JavaScript Development at Application Scale

Object Oriented Programming with TypeScript Tutorial

TypeScript Arrow Function Tutorial

 

comments powered by Disqus