Announcing TypeScript 3.4 | TypeScript

https://devblogs.microsoft.com/typescript/announcing-typescript-3-4/

Avatar

Daniel

Today we’re happy to announce the availability of TypeScript 3.4!

If you haven’t yet used TypeScript, it’s a language that builds on JavaScript that adds optional static types. The TypeScript project provides a compiler that checks your programs based on these types to prevent certain classes of errors, and then strips them out of your program so you can get clean readable JavaScript code that will run in any ECMAScript runtime (like your favorite browser, or Node.js). TypeScript also leverages this type information to provide a language server, which can be used for powerful cross-platform editor tooling like code completions, find-all-references, quick fixes, and refactorings.

TypeScript also provides that same tooling for JavaScript users, and can even type-check JavaScript code typed with JSDoc using the checkJs flag. If you’ve used editors like Visual Studio or Visual Studio Code on a .js file, TypeScript is powering that experience, so you might already be using TypeScript in some capacity!

To get started with TypeScript, you can get it through NuGet, or through npm with the following command:

npm install -g typescript

You can also get editor support by

Support for other editors will likely be rolling in in the near future.

Let’s dive in and see what’s new in TypeScript 3.4!

Faster subsequent builds with the --incremental flag

Because TypeScript files are compiled, there is an intermediate step between writing and running your code. One of our goals is to minimize build time given any change to your program. One way to do that is by running TypeScript in --watch mode. When a file changes under --watch mode, TypeScript is able to use your project’s previously-constructed dependency graph to determine which files could potentially have been affected and need to be re-checked and potentially re-emitted. This can avoid a full type-check and re-emit which can be costly.

But it’s unrealistic to expect all users to keep a tsc --watch process running overnight just to have faster builds tomorrow morning. What about cold builds? Over the past few months, we’ve been working to see if there’s a way to save the appropriate information from --watch mode to a file and use it from build to build.

TypeScript 3.4 introduces a new flag called --incremental which tells TypeScript to save information about the project graph from the last compilation. The next time TypeScript is invoked with --incremental, it will use that information to detect the least costly way to type-check and emit changes to your project.

// tsconfig.json
{
    "compilerOptions": { 
        "incremental": true,
        "outDir": "./lib"
    },
    "include": ["./src"]
}

By default with these settings, when we run tsc, TypeScript will look for a file called .tsbuildinfo in the output directory (./lib). If ./lib/.tsbuildinfo doesn’t exist, it’ll be generated. But if it does, tsc will try to use that file to incrementally type-check and update our output files.

These .tsbuildinfo files can be safely deleted and don’t have any impact on our code at runtime – they’re purely used to make compilations faster. We can also name them anything that we want, and place them anywhere we want using the --tsBuildInfoFile flag.

// front-end.tsconfig.json
{
    "compilerOptions": {
        "incremental": true,
        "tsBuildInfoFile": "./buildcache/front-end",
        "outDir": "./lib"
    },
    "include": ["./src"]
}

As long as nobody else tries writing to the same cache file, we should be able to enjoy faster incremental cold builds.

How fast, you ask? Well, here’s the difference in adding --incremental to the Visual Studio Code project’s tsconfig.json

Step Compile Time
Compile without --incremental 47.54s
First compile with --incremental 52.77s
Subsequent compile with --incremental with API surface change 30.45s
Subsequent compile with --incremental without API surface change 11.49s

For a project the size of Visual Studio Code, TypeScript’s new --incremental flag was able to reduce subsequent build times down to approximately a fifth of the original.

Composite projects

Part of the intent with composite projects (tsconfig.jsons with composite set to true) is that references between different projects can be built incrementally. As such, composite projects will always produce .tsbuildinfo files.

outFile

When outFile is used, the build information file’s name will be based on the output file’s name. As an example, if our output JavaScript file is ./output/foo.js, then under the --incremental flag, TypeScript will generate the file ./output/foo.tsbuildinfo. As above, this can be controlled with the --tsBuildInfoFile flag.

The --incremental file format and versioning

While the file generated by --incremental is JSON, the file isn’t mean to be consumed by any other tool. We can’t provide any guarantees of stability for its contents, and in fact, our current policy is that any one version of TypeScript will not understand .tsbuildinfo files generated from another version.

What else?

That’s pretty much it for --incremental! If you’re interested, check out the pull request (along with its sibling PR) for more details.

In the future, we’ll be investigating APIs for other tools to leverage these generated build information files, as well as enabling the flag for use directly on the command line (as opposed to just in tsconfig.json files).

Higher order type inference from generic functions

TypeScript 3.4 has several improvements around inference that were inspired by some very thoughtful feedback from community member Oliver J. Ash on our issue tracker. One of the biggest improvements relates to functions inferring types from other generic functions.

To get more specific, let’s build up some motivation and consider the following compose function:

function compose<A, B, C>(f: (arg: A) => B, g: (arg: B) => C): (arg: A) => C {
    return x => g(f(x));
}

compose takes two other functions:

  • f which takes some argument (of type A) and returns a value of type B
  • g which takes an argument of type B (the type f returned), and returns a value of type C

compose then returns a function which feeds its argument through f and then g.

When calling this function, TypeScript will try to figure out the types of A, B, and C through a process called type argument inference. This inference process usually works pretty well:

interface Person {
    name: string;
    age: number;
}

function getDisplayName(p: Person) {
    return p.name.toLowerCase();
}

function getLength(s: string) {
    return s.length;
}

// has type '(p: Person) => number'
const getDisplayNameLength = compose(
    getDisplayName,
    getLength,
);

// works and returns the type 'number'
getDisplayNameLength({ name: "Person McPersonface", age: 42 });

The inference process is fairly straightforward here because getDisplayName and getLength use types that can easily be referenced. However, in TypeScript 3.3 and earlier, generic functions like compose didn’t work so well when passed other generic functions.

interface Box<T> {
    value: T;
}

function makeArray<T>(x: T): T[] {
    return [x];
}

function makeBox<U>(value: U): Box<U> {
    return { value };
}

// has type '(arg: {}) => Box<{}[]>'
const makeBoxedArray = compose(
    makeArray,
    makeBox,
)

makeBoxedArray("hello!").value[0].toUpperCase();
//                                ~~~~~~~~~~~
// error: Property 'toUpperCase' does not exist on type '{}'.

Oof! What’s this {} type?

Well, traditionally TypeScript would see that makeArray and makeBox are generic functions, but it couldn’t just infer T and U in the types of A, B, and C. If it did, it would end up with irreconcilable inference candidates T[] and U for B, plus it might have the type variables T and U in the resulting function type, which wouldn’t actually be declared by that resulting type. To avoid this, instead of inferring directly from T and U, TypeScript would infer from the constraints of T and U, which are implicitly the empty object type (that {} type from above).

As you might notice, this behavior isn’t desirable because type information is lost and Ideally, we would infer a better type than {}.

TypeScript 3.4 now does that. During type argument inference for a call to a generic function that returns a function type, TypeScript will, as appropriate, propagate type parameters from generic function arguments onto the resulting function type.

In other words, instead of producing the type

TypeScript 3.4 just “does the right thing” and makes the type

Notice that T has been propagated from makeArray into the resulting type’s type parameter list. This means that genericity from compose‘s arguments has been preserved and our makeBoxedArray sample will just work!

interface Box<T> {
    value: T;
}

function makeArray<T>(x: T): T[] {
    return [x];
}

function makeBox<U>(value: U): Box<U> {
    return { value };
}

// has type '<T>(arg: T) => Box<T[]>'
const makeBoxedArray = compose(
    makeArray,
    makeBox,
)

// works with no problem!
makeBoxedArray("hello!").value[0].toUpperCase();

For more details, you can read more at the original change.

Improvements for ReadonlyArray and readonly tuples

TypeScript 3.4 makes it a little bit easier to use read-only array-like types.

A new syntax for ReadonlyArray

The ReadonlyArray type describes Arrays that can only be read from. Any variable with a reference to a ReadonlyArray can’t add, remove, or replace any elements of the array.

function foo(arr: ReadonlyArray<string>) {
    arr.slice();        // okay
    arr.push("hello!"); // error!
}

While it’s good practice to use ReadonlyArray over Array when no mutation is intended, it’s often been a pain given that arrays have a nicer syntax. Specifically, number[] is a shorthand version of Array<number>, just as Date[] is a shorthand for Array<Date>.

TypeScript 3.4 introduces a new syntax for ReadonlyArray using a new readonly modifier for array types.

function foo(arr: readonly string[]) {
    arr.slice();        // okay
    arr.push("hello!"); // error!
}

readonly tuples

TypeScript 3.4 also introduces new support for readonly tuples. We can prefix any tuple type with the readonly keyword to make it a readonly tuple, much like we now can with array shorthand syntax. As you might expect, unlike ordinary tuples whose slots could be written to, readonly tuples only permit reading from those positions.

function foo(pair: readonly [string, string]) {
    console.log(pair[0]);   // okay
    pair[1] = "hello!";     // error
}

The same way that ordinary tuples are types that extend from Array – a tuple with elements of type T1, T2, … Tn extends from Array< T1 | T2 | … Tn >readonly tuples are types that extend from ReadonlyArray. So a readonly tuple with elements T1, T2, … Tn extends from ReadonlyArray< T1 | T2 | … Tn >.

readonly mapped type modifiers and readonly arrays

In earlier versions of TypeScript, we generalized mapped types to operate differently on array-like types. This meant that a mapped type like Boxify could work on arrays and tuples alike.

interface Box<T> { value: T }

type Boxify<T> = {
    [K in keyof T]: Box<T[K]>
}

// { a: Box<string>, b: Box<number> }
type A = Boxify<{ a: string, b: number }>;

// Array<Box<number>>
type B = Boxify<number[]>;

// [Box<string>, Box<number>]
type C = Boxify<[string, boolean]>;

Unfortunately, mapped types like the Readonly utility type were effectively no-ops on array and tuple types.

// lib.d.ts
type Readonly<T> = {
    readonly [K in keyof T]: T[K]
}

// How code acted *before* TypeScript 3.4

// { readonly a: string, readonly b: number }
type A = Readonly<{ a: string, b: number }>;

// number[]
type B = Readonly<number[]>;

// [string, boolean]
type C = Readonly<[string, boolean]>;

In TypeScript 3.4, the readonly modifier in a mapped type will automatically convert array-like types to their corresponding readonly counterparts.

// How code acts now *with* TypeScript 3.4

// { readonly a: string, readonly b: number }
type A = Readonly<{ a: string, b: number }>;

// readonly number[]
type B = Readonly<number[]>;

// readonly [string, boolean]
type C = Readonly<[string, boolean]>;

Similarly, you could write a utility type like Writable mapped type that strips away readonly-ness, and that would convert readonly array containers back to their mutable equivalents.

type Writable<T> = {
    -readonly [K in keyof T]: T[K]
}

// { a: string, b: number }
type A = Writable<{
    readonly a: string;
    readonly b: number
}>;

// number[]
type B = Writable<readonly number[]>;

// [string, boolean]
type C = Writable<readonly [string, boolean]>;

Caveats

Despite its appearance, the readonly type modifier can only be used for syntax on array types and tuple types. It is not a general-purpose type operator.

let err1: readonly Set<number>; // error!
let err2: readonly Array<boolean>; // error!

let okay: readonly boolean[]; // works fine

You can see more details in the pull request.

const assertions

When declaring a mutable variable or property, TypeScript often widens values to make sure that we can assign things later on without writing an explicit type.

let x = "hello";

// hurray! we can assign to 'x' later on!
x = "world";

Technically, every literal value has a literal type. Above, the type "hello" got widened to the type string before inferring a type for x.

One alternative view might be to say that x has the original literal type "hello" and that we can’t assign "world" later on like so:

let x: "hello" = "hello";

// error!
x = "world";

In this case, that seems extreme, but it can be useful in other situations. For example, TypeScript users often create objects that are meant to be used in discriminated unions.

type Shape =
    | { kind: "circle", radius: number }
    | { kind: "square", sideLength: number }

function getShapes(): readonly Shape[] {
    let result = [
        { kind: "circle", radius: 100, },
        { kind: "square", sideLength: 50, },
    ];
    
    // Some terrible error message because TypeScript inferred
    // 'kind' to have the type 'string' instead of
    // either '"circle"' or '"square"'.
    return result;
}

Mutability is one of the best heuristics of intent which TypeScript can use to determine when to widen (rather than analyzing our entire program).

Unfortunately, as we saw in the last example, in JavaScript properties are mutable by default. This means that the language will often widen types undesirably, requiring explicit types in certain places.

function getShapes(): readonly Shape[] {
    // This explicit annotation gives a hint
    // to avoid widening in the first place.
    let result: readonly Shape[] = [
        { kind: "circle", radius: 100, },
        { kind: "square", sideLength: 50, },
    ];
    
    return result;
}

Up to a certain point this is okay, but as our data structures get more and more complex, this becomes cumbersome.

To solve this, TypeScript 3.4 introduces a new construct for literal values called const assertions. Its syntax is a type assertion with const in place of the type name (e.g. 123 as const). When we construct new literal expressions with const assertions, we can signal to the language that

  • no literal types in that expression should be widened (e.g. no going from "hello" to string)
  • object literals get readonly properties
  • array literals become readonly tuples
// Type '10'
let x = 10 as const;

// Type 'readonly [10, 20]'
let y = [10, 20] as const;

// Type '{ readonly text: "hello" }'
let z = { text: "hello" } as const;

Outside of .tsx files, the angle bracket assertion syntax can also be used.

// Type '10'
let x = <const>10;

// Type 'readonly [10, 20]'
let y = <const>[10, 20];

// Type '{ readonly text: "hello" }'
let z = <const>{ text: "hello" };

This feature means that types that would otherwise be used just to hint immutability to the compiler can often be omitted.

// Works with no types referenced or declared.
// We only needed a single const assertion.
function getShapes() {
    let result = [
        { kind: "circle", radius: 100, },
        { kind: "square", sideLength: 50, },
    ] as const;
    
    return result;
}

for (const shape of getShapes()) {
    // Narrows perfectly!
    if (shape.kind === "circle") {
        console.log("Circle radius", shape.radius);
    }
    else {
        console.log("Square side length", shape.sideLength);
    }
}

Notice the above needed no type annotations. The const assertion allowed TypeScript to take the most specific type of the expression.

This can even be used to enable enum-like patterns in plain JavaScript code if you choose not to use TypeScript’s enum construct.

export const Colors = {
    red: "RED",
    blue: "BLUE",
    green: "GREEN",
} as const;

// or use an 'export default'

export default {
    red: "RED",
    blue: "BLUE",
    green: "GREEN",
} as const;

Caveats

One thing to note is that const assertions can only be applied immediately on simple literal expressions.

// Error! A 'const' assertion can only be applied to a
// to a string, number, boolean, array, or object literal.
let a = (Math.random() < 0.5 ? 0 : 1) as const;

// Works!
let b = Math.random() < 0.5 ?
    0 as const :
    1 as const;

Another thing to keep in mind is that const contexts don’t immediately convert an expression to be fully immutable.

let arr = [1, 2, 3, 4];

let foo = {
    name: "foo",
    contents: arr,
} as const;

foo.name = "bar";   // error!
foo.contents = [];  // error!

foo.contents.push(5); // ...works!

For more details, you can check out the respective pull request.

Type-checking for globalThis

It can be surprisingly difficult to access or declare values in the global scope, perhaps because we’re writing our code in modules (whose local declarations don’t leak by default), or because we might have a local variable that shadows the name of a global value. In different environments, there are different ways to access what’s effectively the global scope – global in Node, window, self, or frames in the browser, or this in certain locations outside of strict mode. None of this is obvious, and often leaves users feeling unsure of whether they’re writing correct code.

TypeScript 3.4 introduces support for type-checking ECMAScript’s new globalThis – a global variable that, well, refers to the global scope. Unlike the above solutions, globalThis provides a standard way for accessing the global scope which can be used across different environments.

// in a global file:

var abc = 100;

// Refers to 'abc' from above.
globalThis.abc = 200;

Note that global variables declared with let and const don’t show up on globalThis.

let answer = 42;

// error! Property 'answer' does not exist on 'typeof globalThis'.
globalThis.answer = 333333;

It’s also important to note that TypeScript doesn’t transform references to globalThis when compiling to older versions of ECMAScript. As such, unless you’re targeting evergreen browsers (which already support globalThis), you may want to use an appropriate polyfill instead.

For more details on the implementation, see the feature’s pull request.

Convert parameters to destructured object

Sometimes, parameter lists start getting unwieldy.

function updateOptions(
    hue?: number,
    saturation?: number,
    brightness?: number,
    positionX?: number,
    positionY?: number,
    positionZ?: number,) {
    
    // ....
}

In the above example, it’s way too easy for a caller to mix up the order of arguments given. A common JavaScript pattern is to instead use an “options object”, so that each option is explicitly named and order doesn’t ever matter. This emulates a feature that other languages have called “named parameters”.

interface Options {
    hue?: number,
    saturation?: number,
    brightness?: number,
    positionX?: number,
    positionY?: number,
    positionZ?: number,
}

function updateOptions(options: Options = {}) {
    
    // ....
}

In TypeScript 3.4, our intern Gabriela Britto has implemented a new refactoring to convert existing functions to use this “named parameters” pattern.

A refactoring being applied to a function to make it take a destructured object.

In the presence of multiple parameters, TypeScript will provide a refactoring to convert the parameter list into a single destructured object. Accordingly, each site where a function is called will also be updated. Features like optionality and defaults are also tracked, and this feature also works on constructors as well.

Currently the refactoring doesn’t generate a name for the type, but we’re interested in hearing feedback as to whether that’s desirable, or whether providing it separately through an upcoming refactoring would be better.

For more details on this refactoring, check out the pull request.

Breaking changes

While it’s never ideal, TypeScript 3.4 does introduce some breaking changes – some simply due to improvements in inference. You can see slightly more detailed explanations on our Breaking Changes page.

Propagated generic type arguments

In certain cases, TypeScript 3.4’s improved inference might produce functions that are generic, rather than ones that take and return their constraints (usually {}).

declare function compose<T, U, V>(f: (arg: T) => U, g: (arg: U) => V): (arg: T) => V;

function list<T>(x: T) { return [x]; }
function box<T>(value: T) { return { value }; }

let f = compose(list, box);
let x = f(100)

// In TypeScript 3.4, 'x.value' has the type
//
//   number[]
//
// but it previously had the type
//
//   {}[]
//
// So it's now an error to push in a string.
x.value.push("hello");

An explicit type annotation on x can get rid of the error.

Contextual return types flow in as contextual argument types

TypeScript now uses types that flow into function calls (like then in the below example) to contextually type function arguments (like the arrow function in the below example).

function isEven(prom: Promise<number>): Promise<{ success: boolean }> {
    return prom.then((x) => {
        return x % 2 === 0 ?
            { success: true } :
            Promise.resolve({ success: false });
    });
}

This is generally an improvement, but in the above example it causes true and false to acquire literal types which is undesirable.

The appropriate workaround is to add type arguments to the appropriate call – the then method call in this example.

function isEven(prom: Promise<number>): Promise<{ success: boolean }> {
    //               vvvvvvvvvvvvvvvvvvvv
    return prom.then<{ success: boolean }>((x) => {
        return x % 2 === 0 ?
            { success: true } :
            Promise.resolve({ success: false });
    });
}

Consistent inference priorities outside of strictFunctionTypes

In TypeScript 3.3 with --strictFunctionTypes off, generic types declared with interface were assumed to always be covariant with respect to their type parameter. For function types, this behavior was generally not observable. However, for generic interface types that used their type parameters with keyof positions – a contravariant use – these types behaved incorrectly.

In TypeScript 3.4, variance of types declared with interface is now correctly measured in all cases. This causes an observable breaking change for interfaces that used a type parameter only in keyof (including places like Record<K, T> which is an alias for a type involving keyof K). The example above is one such possible break.

interface HasX { x: any }
interface HasY { y: any }

declare const source: HasX | HasY;
declare const properties: KeyContainer<HasX>;

interface KeyContainer<T> {
    key: keyof T;
}

function readKey<T>(source: T, prop: KeyContainer<T>) {
    console.log(source[prop.key])
}

// This call should have been rejected, because we might
// incorrectly be reading 'x' from 'HasY'. It now appropriately errors.
readKey(source, properties);

This error is likely indicative of an issue with the original code.

Top-level this is now typed

The type of top-level this is now typed as typeof globalThis instead of any. As a consequence, you may receive errors for accessing unknown values on this under noImplicitAny.

// previously okay in noImplicitAny, now an error
this.whargarbl = 10;

Note that code compiled under noImplicitThis will not experience any changes here.

What’s next?

The TypeScript team has recently started to publish our iteration plans – write-ups of features considered, committed work items, and targeted release dates for a given release. To get an idea of what’s next, you can check out the 3.5 iteration plan document, as well as the rolling feature roadmap page. Based on our planning, some key highlights of 3.5 might include .d.ts file emit from JavaScript projects, and several editor productivity features.

We hope that TypeScript continues to make coding a joy. If you’re happy with this release, let us know on Twitter, and if you’ve got any suggestions on what we can improve, feel free to file an issue on GitHub.

Happy hacking!

– Daniel Rosenwasser and the TypeScript team

Avatar

Leave a Reply

Your email address will not be published. Required fields are marked *

Next Post

Sometimes you have to stick a screwdriver in it (or how to liberate a Chromebook in ten easy steps)

Sat Mar 30 , 2019
https://ar.al/2018/12/31/sometimes-you-have-to-stick-a-screwdriver-in-it/

You May Like