TypeScript 5.3 RC 发布

2023年 11月 5日 42.5k 0

TypeScript 5.3 RC 版本现已发布。可以通过 NuGet 获取,或通过 npm 使用以下命令获取:

npm install -D typescript@rc

TypeScript 5.3 中的新特性包括:

  • Import Attributes
  • 在 Import Types 中稳定支持resolution-mode
  • resolution-mode在所有模块模式均受支持
  • switch (true)Narrowing
  • Narrowing On Comparisons to Booleans
  • instanceof Narrowing Through Symbol.hasInstance
  • 检查对实例字段的 super 属性访问
  • 针对类型的交互式嵌套提示 (Interactive Inlay Hints)
  • PrefertypeAuto-Imports 的设置
  • 通过跳过 JSDoc 解析进行优化
  • 通过 Comparing Non-Normalized Intersections 进行优化
  • 合并tsserverlibrary.jstypescript.js
  • Breaking Changes 和 Correctness Improvements

自 Beta 版以来的新变化有:

Beta 版允许resolution-mode跨模块分辨率设置使用,但并未对此进行记录。自 Beta 版发布以来,项目团队添加了一个选项,在可能的情况下首选type-only auto-imports。

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

更多详情可查看发布公告。

相关文章

塑造我成为 CTO 之路的“秘诀”
“人工智能教母”的公司估值达 10 亿美金
教授吐槽:985 高校成高级蓝翔!研究生基本废了,只为房子、票子……
Windows 蓝屏中断提醒开发者:Rust 比 C/C++ 更好
Claude 3.5 Sonnet 在伽利略幻觉指数中名列前茅
上海新增 11 款已完成登记生成式 AI 服务

发布评论