BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage News TypeScript 2.2 Adds New Object Type, Better Mixin Support, and More

TypeScript 2.2 Adds New Object Type, Better Mixin Support, and More

This item in japanese

Scheduled to be released sometime in February, TypeScript 2.2 has reached RC status. Besides a new JSX emit mode for React Native, it also includes a new object type to represent non-native types, better support for mixins and composable classes, and more.

The new object type provided by TypeScript 2.2 makes it possible to specify method signatures that only accept non-primitive types. This is the case, e.g., with the Object.getPrototypeOf, Object.create etc., which can syntactically accept any kind of object but will throw an exception if they are passed, e.g., a string or a number. The object type allows to catch those kind of misuses at compile-time:

  function mapObject(obj: object): object { /* ... */ }
  ...
  mapObject('string'); // type error

TypeScript 2.2 also adds more flexibility to the creation of mixins and composable types. For example, you can now create a function that takes the constructor of a Point object, declares a new class that extends Points by adding a timestamp to it, and returns a new TimestampedPoint mixin class, which can be instantiated or extended:

class Point {
  ...
}

export type Constructable = new (...args: any[]) => object;
export function Timestamped<BC extends Constructable>(Base: BC) {
    return class extends Base {
        timestamp = new Date();
    };

const TimestampedPoint = Timestamped(Point);
const p = new TimestampedPoint(10, 10);

class SpecialPoint extends Timestamped(Point) {
  z:  number;
  constructor(x: number, y: number, z: number) {
    ...
  }

}

TypeScript has long supported the use of JSX, an XML-like language extension without any defined semantics which aims to represents tree structures with attributes. A typical, although not exclusive, usage of JSX is to describe UI components. Up to version 2.1, TypeScript has been able able to handle JSX expressions in tsx files through two specific emit modes: preserve, which retains the JSX expressions so they can be consumed by a later stage, and react, which creates a js file that uses React.createElement. New in version 2.2 is a new react-native mode, which leaves all JSX expressions intact, but generates a js file, as it is required by React Native’s loader.

TypeScript 2.2rc includes more notable changes, such as:

You can try out TypeScript 2.2rc by running:

npm install -g typescript@rc

Rate this Article

Adoption
Style

BT