Faster subsequent builds with the —incremental flag

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.

  1. // tsconfig.json
  2. {
  3. "compilerOptions": {
  4. "incremental": true,
  5. "outDir": "./lib"
  6. },
  7. "include": ["./src"]
  8. }

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.

  1. // front-end.tsconfig.json
  2. {
  3. "compilerOptions": {
  4. "incremental": true,
  5. "tsBuildInfoFile": "./buildcache/front-end",
  6. "outDir": "./lib"
  7. },
  8. "include": ["./src"]
  9. }

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.

Higher order type inference from generic functions

TypeScript 3.4 can now produce generic function types when inference from other generic functions produces free type variables for inferences.This means many function composition patterns now work better in 3.4.

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

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

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:

  1. interface Person {
  2. name: string;
  3. age: number;
  4. }
  5. function getDisplayName(p: Person) {
  6. return p.name.toLowerCase();
  7. }
  8. function getLength(s: string) {
  9. return s.length;
  10. }
  11. // has type '(p: Person) => number'
  12. const getDisplayNameLength = compose(
  13. getDisplayName,
  14. getLength,
  15. );
  16. // works and returns the type 'number'
  17. 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.

  1. interface Box<T> {
  2. value: T;
  3. }
  4. function makeArray<T>(x: T): T[] {
  5. return [x];
  6. }
  7. function makeBox<U>(value: U): Box<U> {
  8. return { value };
  9. }
  10. // has type '(arg: {}) => Box<{}[]>'
  11. const makeBoxedArray = compose(
  12. makeArray,
  13. makeBox,
  14. )
  15. makeBoxedArray("hello!").value[0].toUpperCase();
  16. // ~~~~~~~~~~~
  17. // error: Property 'toUpperCase' does not exist on type '{}'.

In older versions, TypeScript would infer the empty object type ({}) when inferring from other type variables like T and U.

During type argument inference in TypeScript 3.4, 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

  1. (arg: {}) => Box<{}[]>

TypeScript 3.4 produces the type

  1. <T>(arg: T) => Box<T[]>

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!

  1. interface Box<T> {
  2. value: T;
  3. }
  4. function makeArray<T>(x: T): T[] {
  5. return [x];
  6. }
  7. function makeBox<U>(value: U): Box<U> {
  8. return { value };
  9. }
  10. // has type '<T>(arg: T) => Box<T[]>'
  11. const makeBoxedArray = compose(
  12. makeArray,
  13. makeBox,
  14. )
  15. // works with no problem!
  16. 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.

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

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.

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

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.

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

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.

  1. interface Box<T> { value: T }
  2. type Boxify<T> = {
  3. [K in keyof T]: Box<T[K]>
  4. }
  5. // { a: Box<string>, b: Box<number> }
  6. type A = Boxify<{ a: string, b: number }>;
  7. // Array<Box<number>>
  8. type B = Boxify<number[]>;
  9. // [Box<string>, Box<number>]
  10. type C = Boxify<[string, boolean]>;

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

  1. // lib.d.ts
  2. type Readonly<T> = {
  3. readonly [K in keyof T]: T[K]
  4. }
  5. // How code acted *before* TypeScript 3.4
  6. // { readonly a: string, readonly b: number }
  7. type A = Readonly<{ a: string, b: number }>;
  8. // number[]
  9. type B = Readonly<number[]>;
  10. // [string, boolean]
  11. 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.

  1. // How code acts now *with* TypeScript 3.4
  2. // { readonly a: string, readonly b: number }
  3. type A = Readonly<{ a: string, b: number }>;
  4. // readonly number[]
  5. type B = Readonly<number[]>;
  6. // readonly [string, boolean]
  7. 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.

  1. type Writable<T> = {
  2. -readonly [K in keyof T]: T[K]
  3. }
  4. // { a: string, b: number }
  5. type A = Writable<{
  6. readonly a: string;
  7. readonly b: number
  8. }>;
  9. // number[]
  10. type B = Writable<readonly number[]>;
  11. // [string, boolean]
  12. 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.

  1. let err1: readonly Set<number>; // error!
  2. let err2: readonly Array<boolean>; // error!
  3. let okay: readonly boolean[]; // works fine

You can see more details in the pull request.

const assertions

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
  1. // Type '"hello"'
  2. let x = "hello" as const;
  3. // Type 'readonly [10, 20]'
  4. let y = [10, 20] as const;
  5. // Type '{ readonly text: "hello" }'
  6. let z = { text: "hello" } as const;

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

  1. // Type '"hello"'
  2. let x = <const>"hello";
  3. // Type 'readonly [10, 20]'
  4. let y = <const>[10, 20];
  5. // Type '{ readonly text: "hello" }'
  6. 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.

  1. // Works with no types referenced or declared.
  2. // We only needed a single const assertion.
  3. function getShapes() {
  4. let result = [
  5. { kind: "circle", radius: 100, },
  6. { kind: "square", sideLength: 50, },
  7. ] as const;
  8. return result;
  9. }
  10. for (const shape of getShapes()) {
  11. // Narrows perfectly!
  12. if (shape.kind === "circle") {
  13. console.log("Circle radius", shape.radius);
  14. }
  15. else {
  16. console.log("Square side length", shape.sideLength);
  17. }
  18. }

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.

  1. export const Colors = {
  2. red: "RED",
  3. blue: "BLUE",
  4. green: "GREEN",
  5. } as const;
  6. // or use an 'export default'
  7. export default {
  8. red: "RED",
  9. blue: "BLUE",
  10. green: "GREEN",
  11. } as const;

Caveats

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

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

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

  1. let arr = [1, 2, 3, 4];
  2. let foo = {
  3. name: "foo",
  4. contents: arr,
  5. } as const;
  6. foo.name = "bar"; // error!
  7. foo.contents = []; // error!
  8. foo.contents.push(5); // ...works!

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

Type-checking for globalThis

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.

  1. // in a global file:
  2. var abc = 100;
  3. // Refers to 'abc' from above.
  4. globalThis.abc = 200;

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

  1. let answer = 42;
  2. // error! Property 'answer' does not exist on 'typeof globalThis'.
  3. 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.