Announcing TypeScript 4.3 Beta

Daniel Rosenwasser

Today we’re excited to announce our Beta of TypeScript 4.3!

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

npm install typescript@beta

You can also get editor support by

Let’s dive in to what TypeScript 4.3 brings!

Separate Write Types on Properties

In JavaScript, it’s pretty common for APIs to convert values that are passed in before storing them. This often happens with getters and setters too. For example, let’s imagine we’ve got a class with a setter that always converts a value into a number before saving it in a private field.

class Thing {
    #size = 0;
    
    get size() {
        return this.#size;
    }
    set size(value) {
        let num = Number(value);

        // Don't allow NaN and stuff.
        if (!Number.isFinite(num)) {
            this.#size = 0;
            return;
        }

        this.#size = num;
    }
}

How would we type this JavaScript code in TypeScript? Well, technically we don’t have to do anything special here – TypeScript can look at this with no explicit types and can figure out that size is a number.

The problem is that size allows you to assign more than just numbers to it. We could get around this by saying that size has the type unknown or any like in this snippet:

class Thing {
    // ...
    get size(): unknown {
        return this.#size;
    }
}

But that’s no good – unknown forces people reading size to do a type assertion, and any won’t catch any mistakes. If we really want to model APIs that convert values, previous versions of TypeScript forced us to pick between being precise (which makes reading values easier, and writing harder) and being permissive (which makes writing values easier, and reading harder).

That’s why TypeScript 4.3 allows you to specify types for reading and writing to properties.

class Thing {
    #size = 0;

    get size(): number {
        return this.#size;
    }

    set size(value: string | number | boolean) {
        let num = Number(value);

        // Don't allow NaN and stuff.
        if (!Number.isFinite(num)) {
            this.#size = 0;
            return;
        }

        this.#size = num;
    }
}

In the above example, our set accessor takes a broader set of types (strings, booleans, and numbers), but our get accessor always guarantees it will be a number. Now we can finally assign other types to these properties with no errors!

let thing = new Thing();

// Assigning other types to `thing.size` works!
thing.size = "hello";
thing.size = true;
thing.size = 42;

// Reading `thing.size` always produces a number!
let mySize: number = thing.size;

When considering how two properties with the same name relate to each other, TypeScript will only use the “reading” type (e.g. the type on the get accessor above). “Writing” types are only considered when directly writing to a property.

Keep in mind, this isn’t a pattern that’s limited to classes. You can write getters and setters with different types in object literals.

function makeThing(): Thing {
    let size = 0;
    return {
        get size(): number {
            return size;
        },
        set size(value: string | number | boolean) {
            let num = Number(value);

            // Don't allow NaN and stuff.
            if (!Number.isFinite(num)) {
                size = 0;
                return;
            }

            size = num;
        }
    }
}

In fact, we’ve added syntax to interfaces/object types to support different reading/writing types on properties.

// Now valid!
interface Thing {
    get size(): number
    set size(value: number | string | boolean);
}

One limitation of using different types for reading and writing properties is that the type for reading a property has to be assignable to the type that you’re writing. In other words, the getter type has to be assignable to the setter. This ensures some level of consistency, so that a property is always assignable to itself.

For more information on this feature, take a look at the implementing pull request.

override and the --noImplicitOverride Flag

When extending classes in JavaScript, the language makes it super easy (pun intended) to override methods – but unfortunately, there are some mistakes that you can run into.

One big one is missing renames. For example, take the following classes:

class SomeComponent {
    show() {
        // ...
    }
    hide() {
        // ...
    }
}

class SpecializedComponent extends SomeComponent {
    show() {
        // ...
    }
    hide() {
        // ...
    }
}

SpecializedComponent subclasses SomeComponent, and overrides the show and hide methods. What happens if someone decides to rip out show and hide and replace them with a single method?

 class SomeComponent {
-    show() {
-        // ...
-    }
-    hide() {
-        // ...
-    }
+    setVisible(value: boolean) {
+        // ...
+    }
 }
 class SpecializedComponent extends SomeComponent {
     show() {
         // ...
     }
     hide() {
         // ...
     }
 }

Oh no! Our SpecializedComponent didn’t get updated. Now it’s just adding these two useless show and hide methods that probably won’t get called.

Part of the issue here is that a user can’t make it clear whether they meant to add a new method, or to override an existing one. That’s why TypeScript 4.3 adds the override keyword.

class SpecializedComponent extends SomeComponent {
    override show() {
        // ...
    }
    override hide() {
        // ...
    }
}

When a method is marked with override, TypeScript will always make sure that a method with the same name exists in a the base class.

class SomeComponent {
    setVisible(value: boolean) {
        // ...
    }
}
class SpecializedComponent extends SomeComponent {
    override show() {
//  ~~~~~~~~
// Error! This method can't be marked with 'override' because it's not declared in 'SomeComponent'.
        // ...
    }

    // ...
}

This is a big improvement, but it doesn’t help if you forget to write override on a method – and that’s a big mistake users can run into also.

For example, you might accidentally “trample over” a method that exists in a base class without realizing it.

class Base {
    someHelperMethod() {
        // ...
    }
}

class Derived extends Base {
    // Oops! We weren't trying to override here,
    // we just needed to write a local helper method.
    someHelperMethod() {
        // ...
    }
}

That’s why TypeScript 4.3 also provides a new --noImplicitOverride flag. When this option is turned on, it becomes an error to override any method from a superclass unless you explicitly use an override keyword. In that last example, TypeScript would error under --noImplicitOverride, and give us a clue that we probably need to rename our method inside of Derived.

We’d like to extend our thanks to our community for the implementation here. The work for these items was implemented in a pull request by Wenlu Wang, though an earlier pull request implementing only the override keyword by Paul Cody Johnston served as a basis for direction and discussion. We extend our gratitude for putting in the time for these features.

Template String Type Improvements

In recent versions, TypeScript introduced a new type construct: template string types. These are types that either construct new string-like types by concatenating…

type Color = "red" | "blue";
type Quantity = "one" | "two";

type SeussFish = `${Quantity | Color} fish`;
// same as
//   type SeussFish = "one fish" | "two fish"
//                  | "red fish" | "blue fish";

…or match patterns of other string-like types.

declare let s1: `${number}-${number}-${number}`;
declare let s2: `1-2-3`;

// Works!
s1 = s2;

The first change we made is just in when TypeScript will infer a template string type. When a template string is contextually typed by a string-literal-like type (i.e. when TypeScript sees we’re passing a template string to something that takes a literal type) it will try to give that expression a template type.

function bar(s: string): `hello ${string}` {
    // Previously an error, now works!
    return `hello ${s}`;
}

This also kicks in when inferring types, and the type parameter extends string

declare let s: string;
declare function f<T extends string>(x: T): T;

// Previously: string
// Now       : `hello-${string}`
let x2 = f(`hello ${s}`);

The second major change here is that TypeScript can now better-relate, and infer between, different template string types.

To see this, take the following example code:

declare let s1: `${number}-${number}-${number}`;
declare let s2: `1-2-3`;
declare let s3: `${number}-2-3`;

s1 = s2;
s1 = s3;

When checking against a string literal type like on s2, TypeScript could match against the string contents and figure out that s2 was compatible with s1 in the first assignment; however, as soon as it saw another template string, it just gave up. As a result, assignments like s3 to s1 just didn’t work.

TypeScript now actually does the work to prove whether or not each part of a template string can successfully match. You can now mix and match template strings with different substitutions and TypeScript will do a good job to figure out whether they’re really compatible.

declare let s1: `${number}-${number}-${number}`;
declare let s2: `1-2-3`;
declare let s3: `${number}-2-3`;
declare let s4: `1-${number}-3`;
declare let s5: `1-2-${number}`;
declare let s6: `${number}-2-${number}`;

// Now *all of these* work!
s1 = s2;
s1 = s3;
s1 = s4;
s1 = s5;
s1 = s6;

In doing this work, we were also sure to add better inference capabilities. You can see an example of these in action:

declare function foo<V extends string>(arg: `*${V}*`): V;

function test<T extends string>(s: string, n: number, b: boolean, t: T) {
    let x1 = foo("*hello*");            // "hello"
    let x2 = foo("**hello**");          // "*hello*"
    let x3 = foo(`*${s}*` as const);    // string
    let x4 = foo(`*${n}*` as const);    // `${number}`
    let x5 = foo(`*${b}*` as const);    // "true" | "false"
    let x6 = foo(`*${t}*` as const);    // `${T}`
    let x7 = foo(`**${s}**` as const);  // `*${string}*`
}

For more information, see the original pull request on leveraging contextual types, along with the pull request that improved inference and checking between template types.

ECMAScript #private Class Elements

TypeScript 4.3 expands which elements in a class can be given #private #names to make them truly private at run-time. In addition to properties, methods and accessors can also be given private names.

class Foo {
    #someMethod() {
        //...
    }

    get #someValue() {
        return 100;
    }

    publicMethod() {
        // These work.
        // We can access private-named members inside this class.
        this.#someMethod();
        return this.#someValue;
    }
}

new Foo().#someMethod();
//        ~~~~~~~~~~~
// error!
// Property '#someMethod' is not accessible
// outside class 'Foo' because it has a private identifier.

new Foo().#someValue;
//        ~~~~~~~~~~
// error!
// Property '#someValue' is not accessible
// outside class 'Foo' because it has a private identifier.

Even more broadly, static members can now also have private names.

class Foo {
    static #someMethod() {
        // ...
    }
}

Foo.#someMethod();
//  ~~~~~~~~~~~
// error!
// Property '#someMethod' is not accessible
// outside class 'Foo' because it has a private identifier.

This feature was authored in a pull request from our friends at Bloomberg – written by Titian Cernicova-Dragomirand Kubilay Kahveci, with support and expertise from Joey Watts, Rob Palmer, and Tim McClure. We’d like to extend our thanks to all of them!

Always-Truthy Promise Checks

Under strictNullChecks, checking whether a Promise is “truthy” in a conditional will trigger an error.

async function foo(): Promise<boolean> {
    return false;
}

async function bar(): Promise<string> {
    if (foo()) {
    //  ~~~~~
    // Error!
    // This condition will always return true since
    // this 'Promise<boolean>' appears to always be defined.
    // Did you forget to use 'await'?
        return "true";
    }
    return "false";
}

This change was contributed by Jack Works, and we extend our thanks to them!

static Index Signatures

Index signatures allow us set more properties on a value than a type explicitly declares.

class Foo {
    hello = "hello";
    world = 1234;

    // This is an index signature:
    [propName: string]: string | number | undefined;
}

let instance = new Foo();

// Valid assigment
instance["whatever"] = 42;

// Has type 'string | number | undefined'.
let x = instance["something"];

Up until now, an index signature could only be declared on the instance side of a class. Thanks to a pull request from Wenlu Wang, index signatures can now be declared as static.

class Foo {
    static hello = "hello";
    static world = 1234;

    static [propName: string]: string | number | undefined;
}

// Valid.
Foo["whatever"] = 42;

// Has type 'string | number | undefined'
let x = Foo["something"];

The same sorts of rules apply for index signatures on the static side of a class as they do for the instance side – namely, that every other static property has to be compatible with the index signature.

class Foo {
    static prop = true;
    //     ~~~~
    // Error! Property 'prop' of type 'boolean'
    // is not assignable to string index type
    // 'string | number | undefined'.

    static [propName: string]: string | number | undefined;
}

Import Statement Completions

One of the biggest pain-points users run into with import and export statements in JavaScript is the order – specifically that imports are written as

import { func } from "./module.js";

instead of

from "./module.js" import { func };

This causes some pain when writing out a full import statement from scratch because auto-complete wasn’t able to work correctly. For example, if you start writing something like import {, TypeScript has no idea what module you’re planning on importing from, so it couldn’t provide any scoped-down completions.

To alleviate this, we’ve leveraged the power of auto-imports! Auto-imports already deal with the issue of not being able to narrow down completions from a specific module – their whole point is to provide every possible export and automatically insert an import statement at the top of your file.

So when you now start writing an import statement that doesn’t have a path, we’ll provide you with a list of possible imports. When you commit a completion, we’ll complete the full import statement, including the path that you were going to write.

Import statement completions

This work requires editors that specifically support the feature. You’ll be able to try this out by using the latest Insiders versions of Visual Studio Code.

For more information, take a look at the implementing pull request!

TypeScript can now understand @link tags, and will try to resolve declarations that they link to. What this means is that you’ll be able to hover over names within @link tags and get quick information, or use commands like go-to-definition or find-all-references.

For example, you’ll be able to go-to-definition on bar in @link bar in the example below and a TypeScript-supported editor will jump to bar‘s function declaration.

/**
 * This function depends on {@link bar}
 */
function foo() {

}

function bar() {

}

For more information, see the pull request on GitHub!

Breaking Changes

lib.d.ts Changes

As with every TypeScript version, declarations for lib.d.ts (especially the declarations generated for web contexts), have changed. In this release, we leveraged Mozilla’s browser-compat-data to remove APIs that no browser implements. While it is unlike that you are using them, APIs such as Account, AssertionOptions, RTCStatsEventInit, MSGestureEvent, DeviceLightEvent, MSPointerEvent, ServiceWorkerMessageEvent, and WebAuthentication have all been removed from lib.d.ts. This is discussed in some detail here.

Errors on Always-Truthy Promise Checks

Under strictNullChecks, using a Promise that always appears to be defined within a condition check is now considered an error.

declare var p: Promise<number>;

if (p) {
//  ~
// Error!
// This condition will always return true since
// this 'Promise<number>' appears to always be defined.
//
// Did you forget to use 'await'?
}

For more details, see the original change.

Union Enums Cannot Be Compared to Arbitrary Numbers

Certain enums are considered union enums when their members are either automatically filled in, or trivially written. In those cases, an enum can recall each value that it potentially represents.

In TypeScript 4.3, if a value with a union enum type is compared with a numeric literal that it could never be equal to, then the type-checker will issue an error.

enum E {
  A = 0,
  B = 1,
}

function doSomething(x: E) {
  // Error! This condition will always return 'false' since the types 'E' and '-1' have no overlap.
  if (x === -1) {
    // ...
  }
}

As a workaround, you can re-write an annotation to include the appropriate literal type.

enum E {
  A = 0,
  B = 1,
}

// Include -1 in the type, if we're really certain that -1 can come through.
function doSomething(x: E | -1) {
  if (x === -1) {
    // ...
  }
}

You can also use a type-assertion on the value.

enum E {
  A = 0,
  B = 1,
}

function doSomething(x: E) {
  // Use a type asertion on 'x' because we know we're not actually just dealing with values from 'E'.
  if ((x as number) === -1) {
    // ...
  }
}

Alternatively, you can re-declare your enum to have a non-trivial initializer so that any number is both assignable and comparable to that enum. This may be useful if the intent is for the enum to specify a few well-known values.

enum E {
  // the leading + on 0 opts TypeScript out of inferring a union enum.
  A = +0,
  B = 1,
}

For more details, see the original change

What’s Next?

You can keep track of the upcoming release candidate and stable releases by checking up on the TypeScript 4.3 Iteration Plan. We’re looking to get feedback on this beta (or better yet, our nightly releases), so give it a shot today!

Happy Hacking!

– Daniel Rosenwasser and the TypeScript Team

5 comments

Discussion is closed. Login to edit/delete existing comments.

  • Patricio Ezequiel Hondagneu Roig 0

    As always, excellent work, people! I’m really happy to see the separate write types for props finally implemented.

  • f.a.b White 0

    Thanks for the detailed TS release posts!
    A table of content at the top would be helpful to quickly see all the changes at one glance.

  • Alfonso Ramos Gonzalez 0

    Looking at all the improvement in TypeScript makes me wish .NET had a worse type system, so we could build a better one on top.

    • Paulo Pinto 0

      You can achieve much of the same via C++/CLI and F#, but CLR nowadays seems to mean C# Language Runtime.

  • Roman Levytskyi 0

    Hey guys, first of all, thanks for a good feature set in this release!
    I see that comparing enums with numbers is now more strict, however assigning a number to variable which has enum type is still possible.
    For me it’s been annoying for years. Do you plan to fix this?

    enum E {
      A = 0,
    }
    let e: E = -1; // works but shouldn't :(

Feedback usabilla icon