Announcement of new features Typescript 1.4

Original author: Ryan Cavanaugh
  • Transfer
With the release of Typescript 1.3, we focused on improving the type system and adding ECMAScript 6 functionality to TypeScript. Let's look at some of the new features that you can use in the new version.

All the things described in the article are already implemented in the master branch of our repository on Github - you can download it and try them now.



New features allow you to more accurately and easily work with variables that have a different type at runtime. They reduce the number of places where you need to explicitly specify a type, check it, or use a type any. Authors of typing files (.d.ts) can also use these features to describe external libraries. Those who follow the development of the compiler may have noticed that we ourselves use them too.

Association Types


General information


Union types are a powerful way to express a value that one of several types can have. Suppose you might have an API to execute a program that takes command line arguments in the form of stringor string[]. Now you can write like this:

interface RunOptions {
  program: string;
  commandline: string[]|string;
}

Assigning values ​​of this type works intuitively - any value that could be assigned to any of the members of the enumeration will work:

var opts: RunOptions = /* ... */;
opts.commandline = '-hello world'; // OK
opts.commandline = ['-hello', 'world']; // OK
opts.commandline = [42]; // Ошибка: тип number не совместим с string или string[]

When accessing a variable, you can directly use properties that are common to all types in the union:

if(opts.commandline.length === 0) { // У string и string[] есть свойство length
  console.log("Пусто!");
}

Using type constraints, working with a join-type variable is easy and simple:

function formatCommandline(c: string[]|string) {
  if(typeof c === 'string') {
    return c.trim();
  } else {
    return c.join(' ');
  }
}

Type limiters


A common practice in Javascript is to use operators typeofor instanceofto determine the type of value at runtime. Typescript now understands these constructs and uses them in type inference if they are used in a condition block:

var x: any = /* ... */;
if(typeof x === 'string') {
   console.log(x.subtr(1)); // Ошибка: в типе 'string' нет метода 'subtr'
}
// в этой области видимости переменная 'x' все еще типа 'any'
x.unknown(); // OK

This is how you can use it instanceofwith classes and union types:

class Dog { woof() { } }
class Cat { meow() { } }
var pet: Dog|Cat = /* ... */;
if(pet instanceof Dog) {
   pet.woof(); // OK
} else {
   pet.woof(); // Error
}

Stronger generic types


We also decided to make generalized call verification more stringent in some cases. For example, before such a code, oddly enough, compiled without errors:

function equal(lhs: T, rhs: T): boolean {
   return lhs === rhs;
}
// Раньше: никаких ошибок
// Новое поведение: Ошибка - нет общего типа между 'number' и 'string'
var e = equal(42, 'hello');

Improved type inference


Generic types can improve the quality of checks when using arrays and in other places where it is possible to use several different types in the same collection:

var x = [1, 'world']; // x: Array
x[0] = 'hello'; // OK
x[0] = false; // Ошибка - тип 'boolean' не является ни 'number', ни 'string'

Type Aliases


You can declare an alias for a type using the keyword type:

type PrimitiveArray = Array;
type MyNumber = number;
type NgScope = ng.IScope;
type Callback = () => void;

A type alias is its complete synonym; they are completely interchangeable when used.

In the next article, I will talk about the features of ECMAScript 6 that we add to Typescript. To learn more and try for yourself, download the branch masterfrom the Typescript repository on Github , try and share with us.

Translator's Note



Typescript 1.3 introduces the ability to use tuples from arrays. However, automatic type inference does not occur:

// ожидается: [number, string]
// фактически будет: Array
var x = [1, 'world'];

Why did you do that? The automatic inference of tuple types breaks many use cases, for example:

var x = [dog, cat, animal]; // тип для 'x' будет 'Animal[]'
x[0] = new Frog();

If the type of the variable xwere displayed as a tuple [Dog, Cat, Animal], the assignment in the second line would cause an error. The authors considered it more correct to require explicit indication of tuples, and this sounds pretty logical.

In addition, tuples are compatible with enumeration types unilaterally:
var x : [number, string] = [1, "test"];
var y : Array = x; // Все в порядке
x = y; // ошибка: типы совместимы только в одну сторону

Rather, support for these features would hit Resharper!

UPD: Is it time to create a separate hub for Typescript?

Only registered users can participate in the survey. Please come in.

Do you use Typescript?

  • 18.6% Yes, along with other Microsoft products (Visual Studio, .NET) 101
  • 9.7% Yes, on Linux / Mac OS / another system 53
  • 34.9% I would like to try, but until my hands reach 190
  • 9.7% I use other preprocessors (CoffeeScript, LiveScript) 53
  • 18.2% Preprocessors are evil, only native Javascript! 99
  • 8.6% I don't write in JS or anything like that 47

Also popular now: