TypeScript 4.2 Beta 发布

TypeScript 4.2 Beta 已发布。

获取方法

通过 NuGet 或使用以下 npm 命令进行获取:

npm install typescript@beta

还可以在编辑器中通过以下方式获得:

下面简单介绍 TypeScript 4.2 的新功能。

  • 元祖类型的 Rest 元素支持放置在元组中的任何位置

在以前的版本中,TypeScript 仅允许 rest 元素位于元组类型的最后位置,但现在 rest 元素可以在元组中的任何位置出现,唯一的限制是只要它后面没有其他可选元素或 rest 元素即可。换句话说,每个元组仅一个 rest 元素,rest 元素之后没有可选元素。

let foo: [...string[], number];

foo = [123];
foo = ["hello", 123];
foo = ["hello!", "hello!", "hello!", 123];

let bar: [boolean, ...string[], boolean];

bar = [true, false];
bar = [true, "some text", false];
bar = [true, "some", "separated", "text", false];
  • 更智能地保留类型别名
  • 模板字面量表达式已具有模板字面量类型

TypeScript 4.1 引入了一种新的类型:模板字面量类型 (template literal types)。此类型能够对字符串的特定模式进行建模。

type GreetingStart = "hello" | "hi" | "sup";

declare function greet(str: `${GreetingStart} ${string}`): void;

// Works.
greet("hello world!");

// Works.
greet("hi everybody!");

// Error!
// Doesn't work with any of the patterns:
//   `hello ${string}` | `hi ${string}` | `sup ${string}`
greet("hallo yes hi sup");

但在 4.1 中,模板字符串类型和模板字符串表达式之间存在一些奇怪的不一致地方。这是因为模板字符串表达式无法与新的模板字符串类型兼容。

因此在 TypeScript 4.2 中,模板字符串表达式现在总是以模板字面量类型开始。

  • 为 in 运算符执行更严格的检查
  • 放宽可选属性和字符串索引签名之间的规则
  • 声明缺失的辅助功能

详细内容查看发布公告

猜你喜欢

转载自www.oschina.net/news/126465/typescript-4-2-beta-released