BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News TypeScript 2.0 Beta Brings Option Types, Discriminated Unions, and More

TypeScript 2.0 Beta Brings Option Types, Discriminated Unions, and More

This item in japanese

Lire ce contenu en français

Microsoft’s Daniel Rosenwasser has announced the beta release of TypeScript 2.0, which brings a wealth of new features to the language including non-nullable types, control flow analysis for types and discriminated unions.

Non-nullable types aim to solve the most common source of bugs in JavaScript, says Rosenwasser: null and undefined. Non-nullable types forbid assigning null to a variable, unless it is declared as an option type:

let foo1: string = null; // Error!
let foo2: string | null = null; // Option type

As shown above, option types are specified as union types, another new feature in TypeScript 2.0. Optional parameters and properties are automatically inferred as belonging to option types. Option types can be used either through the ! operator, or through type guards:

let s: string | undefined = "string"; // Okay
if (s) {
    f(s);
}
let upperCase = s!.toUpperCase(); // Okay
let lowerCase = foo2.toLowerCase(); // Error

Non-nullable types are enabled in TypeScript 2.0 by using the --strictNullChecks flag.

TypeScript 2.0 also introduces control flow based type analysis for local variables and parameters. This represents a major improvement to TypeScript type analysis and extends pre–2.0 type analysis by including the effects of assignments and control flow constructs, e.g., return, break, etc.

New in TypeScript 2.0 are also private and protected constructors which can be declared using the private and protected keywords. Furthermore, properties can now be abstract, which forces subclasses to provide a definition for their accessors:

abstract class A {
  abstract p;
}
class B extends A {
  get p() {...}
  set p(v) {...}
}

In addition to the null and undefined types mentioned above, TypeScript 2.0 also introduces a new never type, which represents the types of a value that never occur, such as a function that never returns, or a variable under a guard that can never be true:

// Function returning never must have unreachable end point
function error(message: string): never {
    throw new Error(message);
}

There are more new features in TypeScript 2.0, such as read-only properties and index signature, specifying the type of implicit this argument to functions, module resolution enhancement, and many more.

To install TypeScript 2.0 beta, you can download it for Visual Studio 2015 (which will require VS 2015 Update 3). Alternatively, you can run npm install -g typescript@beta.

Rate this Article

Adoption
Style

BT