TypeScript 5.3 正式发布

TypeScript 5.3 已正式发布。

主要变化


import attributes

import attributes 的一个用例是向运行时提供有关模块预期格式的信息。

// 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 不会检查这些属性的内容,因为它们是特定于主机的,因此不会对它们进行检查,只是让浏览器和运行时处理它们(可能会出错)。

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

动态 import () 调用也可以通过第二个参数使用 import 属性。

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

第二个参数的预期类型由一个名为ImportCallOptions的类型定义,默认情况下,该类型只期望调用一个属性with

请注意,导入属性是从早期的 "导入断言"(import assertions)提案演变而来的,该提案已在 TypeScript 4.5 中实现。最明显的区别是使用了with关键字而非assert关键字。但不太明显的区别是,运行时现在可以自由使用属性来指导导入路径的解析和解释,而导入断言只能在加载模块后断言某些特性。

随着时间的推移,TypeScript 将淘汰旧的导入断言语法,转而使用建议的导入属性语法。使用 assert 的现有代码应迁移到 with 关键字。需要导入属性的新代码应只使用with关键字。

switch (true)Narrowing

TypeScript 5.3 可以根据switch (true)中每个case子句的条件执行 narrowing。

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.
          // ...
    }
}

详情查看发布公告

猜你喜欢

转载自www.oschina.net/news/267382/typescript-5-3-ga
5.3