TypeScript Highlights
Microsoft recently released a new, open source language called TypeScript. It is a strict superset of Javascript, and compiles directly to Javascript. The compiler is open source, and written in TypeScript itself. My team at Microsoft has been dogfooding TypeScript for several months now, and I thought I'd share a few of my favorite parts of the language.
Note: you can try out the TypeScript language easily, in your browser, with the TypeScript Playground.
Classes and modules
Per the language specification:
TypeScript syntax includes several proposed features of Ecmascript 6 (ES6), including classes and modules.
Modules can export classes, functions, and variables, and classes can have static and instance members. Classes members can have private or public scope, which is enforced by the compiler. As an example:
export module Sayings {
export class Greeter {
private greeting: string;
constructor(greeting: string) {
this.greeting = greeting;
}
public greet(): void {
alert(this.greeting);
}
}
}
Inheritance
Classes can extend
a single base class to inherit and optionally override all its members. Overridden methods in the derived class must have a compatible signature to the base class implementation.
class A {
x() {
alert('a.x');
}
y() {
alert('a.y');
}
}
class B extends A {
y() {
alert('b.y');
}
}
new A().x(); // prints 'a.x'
new A().y(); // prints 'a.y'
new B().x(); // prints 'a.x'
new B().y(); // prints 'b.y'
Lambdas
Lambdas are not only shortened syntax for the function
keyword, but also capture the this
variable automatically if you are inside a class.
class Greeter {
greeting: string = 'hello ';
public makeGreeter(): (name: string) => string {
return name => this.greeting + name;
}
}
Interfaces and Structural Typing
Interfaces are simple to use with internal and external code, and is checked using structural typing. Classes can implement interfaces to enforce checking, and interfaces can extend other interfaces.
class Greeter {
greet() {
alert('Hello');
}
}
interface IGreeter {
greet();
}
var greeter: IGreeter = new Greeter();
greeter.greet();
Type inference
TypeScript has extensive type inference. In the following example, the function greet will be typed (number) => string
:
class Greet {
greet(x: number) {
var s = ' greetings';
return x + s;
}
}
Static and member vars, return types, local variables, all are type inferred.
Javascript is TypeScript
TypeScript is a superset of Javascript, so converting you codebase is instant. Once you are using the TypeScript compiler, you can begin adding type annotations to enable more robust type checking.