TypeScript 3.8

TypeScript 3.8

  • Type-Only Imports and Exports

  • ECMAScript Private Fields

  • export * as ns Syntax

  • Top-Level await

  • JSDoc Property Modifiers

  • Better Directory Watching on Linux and watchOptions

  • “Fast and Loose” Incremental Checking

类型导入和导出(Type-Only Imports and Exports)

This feature is something most users may never have to think about; however, if you’ve hit issues under --isolatedModules, TypeScript’s transpileModule API, or Babel, this feature might be relevant.

TypeScript 3.8 adds a new syntax for type-only imports and exports.

import type { SomeThing } from "./some-module.js";export type { SomeThing };

import type only imports declarations to be used for type annotations and declarations. It always gets fully erased, so there’s no remnant of it at runtime. Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript’s output.

It’s important to note that classes have a value at runtime and a type at design-time, and the use is context-sensitive. When using import type to import a class, you can’t do things like extend from it.

import type { Component } from "react";interface ButtonProps {    // ...}class Button extends Component<​ButtonProps> {    //               ~~~~~~~~~    // error! 'Component' only refers to a type, but is being used as a value here.    // ...}

If you’ve used Flow before, the syntax is fairly similar. One difference is that we’ve added a few restrictions to avoid code that might appear ambiguous.

// Is only 'Foo' a type? Or every declaration in the import?// We just give an error because it's not clear.import type Foo, { Bar, Baz } from "some-module";//     ~~~~~~~~~~~~~~~~~~~~~~// error! A type-only import can specify a default import or named bindings, but not both.

In conjunction with import type, TypeScript 3.8 also adds a new compiler flag to control what happens with imports that won’t be utilized at runtime: importsNotUsedAsValues. This flag takes 3 different values:

  • remove: this is today’s behavior of dropping these imports. It’s going to continue to be the default, and is a non-breaking change.

  • preserve: this preserves all imports whose values are never used. This can cause imports/side-effects to be preserved.

  • error: this preserves all imports (the same as the preserve option), but will error when a value import is only used as a type. This might be useful if you want to ensure no values are being accidentally imported, but still make side-effect imports explicit.

For more information about the feature, you can take a look at the pull request, and relevant changes around broadening where imports from an import type declaration can be used.

ECMAScript 私有变量(ECMAScript Private Fields

TypeScript 3.8 brings support for ECMAScript’s private fields, part of the stage-3 class fields proposal.

class Person {    #name: string    constructor(name: string) {        this.#name = name;    }    greet() {        console.log(`Hello, my name is ${this.#name}!`);    }}let jeremy = new Person("Jeremy Bearimy");jeremy.#name//     ~~~~~// Property '#name' is not accessible outside class 'Person'// because it has a private identifier.

Unlike regular properties (even ones declared with the private modifier), private fields have a few rules to keep in mind. Some of them are:

  • Private fields start with a # character. Sometimes we call these private names.

  • Every private field name is uniquely scoped to its containing class.

  • TypeScript accessibility modifiers like public or private can’t be used on private fields.

  • Private fields can’t be accessed or even detected outside of the containing class - even by JS users! Sometimes we call this hard privacy.

Apart from “hard” privacy, another benefit of private fields is that uniqueness we just mentioned. For example, regular property declarations are prone to being overwritten in subclasses.

class C {    foo = 10;    cHelper() {        return this.foo;    }}class D extends C {    foo = 20;    dHelper() {        return this.foo;    }}let instance = new D();// 'this.foo' refers to the same property on each instance.console.log(instance.cHelper()); // prints '20'console.log(instance.dHelper()); // prints '20'

With private fields, you’ll never have to worry about this, since each field name is unique to the containing class.

class C {    #foo = 10;    cHelper() {        return this.#foo;    }}class D extends C {    #foo = 20;    dHelper() {        return this.#foo;    }}let instance = new D();// 'this.#foo' refers to a different field within each class.console.log(instance.cHelper()); // prints '10'console.log(instance.dHelper()); // prints '20'

Another thing worth noting is that accessing a private field on any other type will result in a TypeError!

class Square {    #sideLength: number;    constructor(sideLength: number) {        this.#sideLength = sideLength;    }    equals(other: any) {        return this.#sideLength === other.#sideLength;    }}const a = new Square(100);const b = { sideLength: 100 };// Boom!// TypeError: attempted to get private field on non-instance// This fails because 'b' is not an instance of 'Square'.console.log(a.equals(b));

Finally, for any plain .js file users, private fields always have to be declared before they’re assigned to.

class C {    // No declaration for '#foo'    // :(    constructor(foo: number) {        // SyntaxError!        // '#foo' needs to be declared before writing to it.        this.#foo = foo;    }}

JavaScript has always allowed users to access undeclared properties, whereas TypeScript has always required declarations for class properties. With private fields, declarations are always needed regardless of whether we’re working in .js or .ts files.

class C {    /** @type {number} */    #foo;    constructor(foo: number) {        // This works.        this.#foo = foo;    }}

For more information about the implementation, you can check out the original pull request

Which should I use?

We’ve already received many questions on which type of privates you should use as a TypeScript user: most commonly, “should I use the private keyword, or ECMAScript’s hash/pound (#) private fields?” It depends!

When it comes to properties, TypeScript’s private modifiers are fully erased - that means that at runtime, it acts entirely like a normal property and there’s no way to tell that it was declared with a private modifier. When using theprivate` keyword, privacy is only enforced at compile-time/design-time, and for JavaScript consumers it’s entirely intent-based.

class C {    private foo = 10;}// This is an error at compile time,// but when TypeScript outputs .js files,// it'll run fine and print '10'.console.log(new C().foo);    // prints '10'//                  ~~~// error! Property 'foo' is private and only accessible within class 'C'.// TypeScript allows this at compile-time// as a "work-around" to avoid the error.console.log(new C()["foo"]); // prints '10'

The upside is that this sort of “soft privacy” can help your consumers temporarily work around not having access to some API, and also works in any runtime.

On the other hand, ECMAScript’s # privates are completely inaccessible outside of the class.

class C {    #foo = 10;}console.log(new C().#foo); // SyntaxError//                  ~~~~// TypeScript reports an error *and*// this won't work at runtime!console.log(new C()["#foo"]); // prints undefined//          ~~~~~~~~~~~~~~~// TypeScript reports an error under 'noImplicitAny',// and this prints 'undefined'.

This hard privacy is really useful for strictly ensuring that nobody can take use of any of your internals. If you’re a library author, removing or renaming a private field should never cause a breaking change.