TypeScript 5.3 officially released

TypeScript 5.3 has been officially released.

Main changes


import attributes

One use case for import attributes is to provide the runtime with information about the module's expected format.

// We only want this to be interpreted as JSON,
// not a runnable/malicious JavaScript file with a `.json` extension.
import obj from "./something.json" with { type: "json" };

TypeScript does not check the contents of these properties because they are host-specific, so they are not checked and are simply left to the browser and runtime to handle them (potentially with errors).

// TypeScript is fine with this.
// But your browser? Probably not.
import * as foo from "./foo.js" with { type: "fluffy bunny" };

Dynamic import () calls can also use the import attribute via the second parameter.

const obj = await import("./something.json", {
    with: { type: "json" }
});

The expected type of the second argument is ImportCallOptionsdefined by a type named , which by default only expects a property to be called with.

Note that import properties evolved from the earlier proposal for "import assertions", which was implemented in TypeScript 4.5. The most obvious difference is the use of withkeywords instead of assertkeywords. But the less obvious difference is that the runtime is now free to use properties to guide the parsing and interpretation of import paths, whereas import assertions can only assert certain characteristics after the module is loaded.

Over time, TypeScript will deprecate the old import assertion syntax in favor of the recommended import property syntax. Existing code using assert should be migrated to the with keyword. New code that requires imported properties should only use withthe keyword.

switch (true)Narrowing

TypeScript 5.3 can perform narrowing based on conditions switch (true)in each caseclause.

function f(x: unknown) {
    switch (true) {
        case typeof x === "string":
            // 'x' is a 'string' here
            console.log(x.toUpperCase());
            // falls through...

        case Array.isArray(x):
            // 'x' is a 'string | any[]' here.
            console.log(x.length);
            // falls through...

        default:
          // 'x' is 'unknown' here.
          // ...
    }
}

See the release announcement for details .

おすすめ

転載: www.oschina.net/news/267382/typescript-5-3-ga