JSX support

JSX is an embeddable XML-like syntax.It is meant to be transformed into valid JavaScript, but the semantics of that transformation are implementation-specific.JSX came to popularity with the React library but has since seen other applications.TypeScript 1.6 supports embedding, type checking, and optionally compiling JSX directly into JavaScript.

New .tsx file extension and as operator

TypeScript 1.6 introduces a new .tsx file extension.This extension does two things: it enables JSX inside of TypeScript files, and it makes the new as operator the default way to cast (removing any ambiguity between JSX expressions and the TypeScript prefix cast operator).For example:

  1. var x = <any> foo;
  2. // is equivalent to:
  3. var x = foo as any;

Using React

To use JSX-support with React you should use the React typings. These typings define the JSX namespace so that TypeScript can correctly check JSX expressions for React. For example:

  1. /// <reference path="react.d.ts" />
  2. interface Props {
  3. name: string;
  4. }
  5. class MyComponent extends React.Component<Props, {}> {
  6. render() {
  7. return <span>{this.props.foo}</span>
  8. }
  9. }
  10. <MyComponent name="bar" />; // OK
  11. <MyComponent name={0} />; // error, `name` is not a number

Using other JSX framworks

JSX element names and properties are validated against the JSX namespace.Please see the [[JSX]] wiki page for defining the JSX namespace for your framework.

Output generation

TypeScript ships with two JSX modes: preserve and react.

  • The preserve mode will keep JSX expressions as part of the output to be further consumed by another transform step. Additionally the output will have a .jsx file extension.
  • The react mode will emit React.createElement, does not need to go through a JSX transformation before use, and the output will have a .js file extension.See the [[JSX]] wiki page for more information on using JSX in TypeScript.

Intersection types

TypeScript 1.6 introduces intersection types, the logical complement of union types.A union type A | B represents an entity that is either of type A or type B, whereas an intersection type A & B represents an entity that is both of type A and type B.

Example
  1. function extend<T, U>(first: T, second: U): T & U {
  2. let result = <T & U> {};
  3. for (let id in first) {
  4. result[id] = first[id];
  5. }
  6. for (let id in second) {
  7. if (!result.hasOwnProperty(id)) {
  8. result[id] = second[id];
  9. }
  10. }
  11. return result;
  12. }
  13. var x = extend({ a: "hello" }, { b: 42 });
  14. var s = x.a;
  15. var n = x.b;
  1. type LinkedList<T> = T & { next: LinkedList<T> };
  2. interface Person {
  3. name: string;
  4. }
  5. var people: LinkedList<Person>;
  6. var s = people.name;
  7. var s = people.next.name;
  8. var s = people.next.next.name;
  9. var s = people.next.next.next.name;
  1. interface A { a: string }
  2. interface B { b: string }
  3. interface C { c: string }
  4. var abc: A & B & C;
  5. abc.a = "hello";
  6. abc.b = "hello";
  7. abc.c = "hello";

See issue #1256 for more information.

Local type declarations

Local class, interface, enum, and type alias declarations can now appear inside function declarations. Local types are block scoped, similar to variables declared with let and const. For example:

  1. function f() {
  2. if (true) {
  3. interface T { x: number }
  4. let v: T;
  5. v.x = 5;
  6. }
  7. else {
  8. interface T { x: string }
  9. let v: T;
  10. v.x = "hello";
  11. }
  12. }

The inferred return type of a function may be a type declared locally within the function. It is not possible for callers of the function to reference such a local type, but it can of course be matched structurally. For example:

  1. interface Point {
  2. x: number;
  3. y: number;
  4. }
  5. function getPointFactory(x: number, y: number) {
  6. class P {
  7. x = x;
  8. y = y;
  9. }
  10. return P;
  11. }
  12. var PointZero = getPointFactory(0, 0);
  13. var PointOne = getPointFactory(1, 1);
  14. var p1 = new PointZero();
  15. var p2 = new PointZero();
  16. var p3 = new PointOne();

Local types may reference enclosing type parameters and local class and interfaces may themselves be generic. For example:

  1. function f3() {
  2. function f<X, Y>(x: X, y: Y) {
  3. class C {
  4. public x = x;
  5. public y = y;
  6. }
  7. return C;
  8. }
  9. let C = f(10, "hello");
  10. let v = new C();
  11. let x = v.x; // number
  12. let y = v.y; // string
  13. }

Class expressions

TypeScript 1.6 adds support for ES6 class expressions. In a class expression, the class name is optional and, if specified, is only in scope in the class expression itself. This is similar to the optional name of a function expression. It is not possible to refer to the class instance type of a class expression outside the class expression, but the type can of course be matched structurally. For example:

  1. let Point = class {
  2. constructor(public x: number, public y: number) { }
  3. public length() {
  4. return Math.sqrt(this.x * this.x + this.y * this.y);
  5. }
  6. };
  7. var p = new Point(3, 4); // p has anonymous class type
  8. console.log(p.length());

Extending expressions

TypeScript 1.6 adds support for classes extending arbitrary expression that computes a constructor function. This means that built-in types can now be extended in class declarations.

The extends clause of a class previously required a type reference to be specified. It now accepts an expression optionally followed by a type argument list. The type of the expression must be a constructor function type with at least one construct signature that has the same number of type parameters as the number of type arguments specified in the extends clause. The return type of the matching construct signature(s) is the base type from which the class instance type inherits. Effectively, this allows both real classes and “class-like” expressions to be specified in the extends clause.

Some examples:

  1. // Extend built-in types
  2. class MyArray extends Array<number> { }
  3. class MyError extends Error { }
  4. // Extend computed base class
  5. class ThingA {
  6. getGreeting() { return "Hello from A"; }
  7. }
  8. class ThingB {
  9. getGreeting() { return "Hello from B"; }
  10. }
  11. interface Greeter {
  12. getGreeting(): string;
  13. }
  14. interface GreeterConstructor {
  15. new (): Greeter;
  16. }
  17. function getGreeterBase(): GreeterConstructor {
  18. return Math.random() >= 0.5 ? ThingA : ThingB;
  19. }
  20. class Test extends getGreeterBase() {
  21. sayHello() {
  22. console.log(this.getGreeting());
  23. }
  24. }

abstract classes and methods

TypeScript 1.6 adds support for abstract keyword for classes and their methods. An abstract class is allowed to have methods with no implementation, and cannot be constructed.

Examples
  1. abstract class Base {
  2. abstract getThing(): string;
  3. getOtherThing() { return 'hello'; }
  4. }
  5. let x = new Base(); // Error, 'Base' is abstract
  6. // Error, must either be 'abstract' or implement concrete 'getThing'
  7. class Derived1 extends Base { }
  8. class Derived2 extends Base {
  9. getThing() { return 'hello'; }
  10. foo() {
  11. super.getThing();// Error: cannot invoke abstract members through 'super'
  12. }
  13. }
  14. var x = new Derived2(); // OK
  15. var y: Base = new Derived2(); // Also OK
  16. y.getThing(); // OK
  17. y.getOtherThing(); // OK

Generic type aliases

With TypeScript 1.6, type aliases can be generic. For example:

  1. type Lazy<T> = T | (() => T);
  2. var s: Lazy<string>;
  3. s = "eager";
  4. s = () => "lazy";
  5. interface Tuple<A, B> {
  6. a: A;
  7. b: B;
  8. }
  9. type Pair<T> = Tuple<T, T>;

Stricter object literal assignment checks

TypeScript 1.6 enforces stricter object literal assignment checks for the purpose of catching excess or misspelled properties. Specifically, when a fresh object literal is assigned to a variable or passed as an argument for a non-empty target type, it is an error for the object literal to specify properties that don’t exist in the target type.

Examples
  1. var x: { foo: number };
  2. x = { foo: 1, baz: 2 }; // Error, excess property `baz`
  3. var y: { foo: number, bar?: number };
  4. y = { foo: 1, baz: 2 }; // Error, excess or misspelled property `baz`

A type can include an index signature to explicitly indicate that excess properties are permitted:

  1. var x: { foo: number, [x: string]: any };
  2. x = { foo: 1, baz: 2 }; // Ok, `baz` matched by index signature

ES6 generators

TypeScript 1.6 adds support for generators when targeting ES6.

A generator function can have a return type annotation, just like a function. The annotation represents the type of the generator returned by the function. Here is an example:

  1. function *g(): Iterable<string> {
  2. for (var i = 0; i < 100; i++) {
  3. yield ""; // string is assignable to string
  4. }
  5. yield * otherStringGenerator(); // otherStringGenerator must be iterable and element type assignable to string
  6. }

A generator function with no type annotation can have the type annotation inferred.So in the following case, the type will be inferred from the yield statements:

  1. function *g() {
  2. for (var i = 0; i < 100; i++) {
  3. yield ""; // infer string
  4. }
  5. yield * otherStringGenerator(); // infer element type of otherStringGenerator
  6. }

Experimental support for async functions

TypeScript 1.6 introduces experimental support of async functions when targeting ES6.Async functions are expected to invoke an asynchronous operation and await its result without blocking normal execution of the program.This accomplished through the use of an ES6-compatible Promise implementation, and transposition of the function body into a compatible form to resume execution when the awaited asynchronous operation completes.

An async function is a function or method that has been prefixed with the async modifier. This modifier informs the compiler that function body transposition is required, and that the keyword await should be treated as a unary expression instead of an identifier.An Async Function must provide a return type annotation that points to a compatible Promise type. Return type inference can only be used if there is a globally defined, compatible Promise type.

Example
  1. var p: Promise<number> = /* ... */;
  2. async function fn(): Promise<number> {
  3. var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
  4. return 1 + i;
  5. }
  6. var a = async (): Promise<number> => 1 + await p; // suspends execution.
  7. var a = async () => 1 + await p; // suspends execution. return type is inferred as "Promise<number>" when compiling with --target ES6
  8. var fe = async function(): Promise<number> {
  9. var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
  10. return 1 + i;
  11. }
  12. class C {
  13. async m(): Promise<number> {
  14. var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
  15. return 1 + i;
  16. }
  17. async get p(): Promise<number> {
  18. var i = await p; // suspend execution until 'p' is settled. 'i' has type "number"
  19. return 1 + i;
  20. }
  21. }

Nightly builds

While not strictly a language change, nightly builds are now available by installing with the following command:

  1. npm install -g typescript@next

Adjustments in module resolution logic

Starting from release 1.6 TypeScript compiler will use different set of rules to resolve module names when targeting ‘commonjs’.These rules attempted to model module lookup procedure used by Node.This effectively mean that node modules can include information about its typings and TypeScript compiler will be able to find it.User however can override module resolution rules picked by the compiler by using —moduleResolution command line option. Possible values are:

  • ‘classic’ - module resolution rules used by pre 1.6 TypeScript compiler
  • ‘node’ - node-like module resolution

Merging ambient class and interface declaration

The instance side of an ambient class declaration can be extended using an interface declaration The class constructor object is unmodified.For example:

  1. declare class Foo {
  2. public x : number;
  3. }
  4. interface Foo {
  5. y : string;
  6. }
  7. function bar(foo : Foo) {
  8. foo.x = 1; // OK, declared in the class Foo
  9. foo.y = "1"; // OK, declared in the interface Foo
  10. }

User-defined type guard functions

TypeScript 1.6 adds a new way to narrow a variable type inside an if block, in addition to typeof and instanceof.A user-defined type guard functions is one with a return type annotation of the form x is T, where x is a declared parameter in the signature, and T is any type.When a user-defined type guard function is invoked on a variable in an if block, the type of the variable will be narrowed to T.

Examples
  1. function isCat(a: any): a is Cat {
  2. return a.name === 'kitty';
  3. }
  4. var x: Cat | Dog;
  5. if(isCat(x)) {
  6. x.meow(); // OK, x is Cat in this block
  7. }

exclude property support in tsconfig.json

A tsconfig.json file that doesn’t specify a files property (and therefore implicitly references all *.ts files in all subdirectories) can now contain an exclude property that specifies a list of files and/or directories to exclude from the compilation.The exclude property must be an array of strings that each specify a file or folder name relative to the location of the tsconfig.json file.For example:

  1. {
  2. "compilerOptions": {
  3. "out": "test.js"
  4. },
  5. "exclude": [
  6. "node_modules",
  7. "test.ts",
  8. "utils/t2.ts"
  9. ]
  10. }

The exclude list does not support wilcards. It must simply be a list of files and/or directories.

—init command line option

Run tsc —init in a directory to create an initial tsconfig.json in this directory with preset defaults.Optionally pass command line arguments along with —init to be stored in your initial tsconfig.json on creation.