TypeScript 5.0

装饰器

🌐 Decorators

装饰器是即将推出的 ECMAScript 功能,它允许我们以可重用的方式自定义类及其成员。

🌐 Decorators are an upcoming ECMAScript feature that allow us to customize classes and their members in a reusable way.

让我们考虑以下代码:

🌐 Let’s consider the following code:

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const p = new Person("Ray");
p.greet();

greet 在这里相当简单,但我们假设它是某个更复杂的东西——也许它执行一些异步逻辑,它是递归的,或者它有副作用等等。无论你想象的是哪种复杂情况,我们假设你加入一些 console.log 调用来帮助调试 greet

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet() {
console.log("LOG: Entering method.");
console.log(`Hello, my name is ${this.name}.`);
console.log("LOG: Exiting method.")
}
}

这种模式相当常见。如果能有一种方法让我们对每个方法都这样做,那就太好了!

🌐 This pattern is fairly common. It sure would be nice if there was a way we could do this for every method!

这就是装饰器发挥作用的地方。我们可以编写一个名为 loggedMethod 的函数,看起来如下所示:

🌐 This is where decorators come in. We can write a function called loggedMethod that looks like the following:

ts
function loggedMethod(originalMethod: any, _context: any) {
function replacementMethod(this: any, ...args: any[]) {
console.log("LOG: Entering method.")
const result = originalMethod.call(this, ...args);
console.log("LOG: Exiting method.")
return result;
}
return replacementMethod;
}

这些 any 都是怎么回事?这是 any 脚本吗!?

只需耐心——我们现在保持简单,以便能够专注于这个函数的具体作用。请注意,loggedMethod 接收原始方法 (originalMethod) 并返回一个函数,该函数

🌐 Just be patient - we’re keeping things simple for now so that we can focus on what this function is doing. Notice that loggedMethod takes the original method (originalMethod) and returns a function that

  1. 记录“正在进入…”消息
  2. this 及其所有参数传递给原方法
  3. 记录一个“正在退出……”的消息,并
  4. 返回原始方法返回的内容。

现在我们可以使用 loggedMethod装饰方法 greet:

🌐 Now we can use loggedMethod to decorate the method greet:

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
@loggedMethod
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const p = new Person("Ray");
p.greet();
// Output:
//
// LOG: Entering method.
// Hello, my name is Ray.
// LOG: Exiting method.

我们刚刚在 greet 上方使用了 loggedMethod 作为装饰器——请注意我们将其写成了 @loggedMethod。 当我们这么做时,它会被调用,并传入方法 target 和一个 context 对象。 因为 loggedMethod 返回了一个新函数,所以这个函数替换了 greet 的原始定义。

🌐 We just used loggedMethod as a decorator above greet - and notice that we wrote it as @loggedMethod. When we did that, it got called with the method target and a context object. Because loggedMethod returned a new function, that function replaced the original definition of greet.

我们还没有提到,但 loggedMethod 是用第二个参数定义的。它被称为“上下文对象”,里面包含了一些关于被装饰方法是如何声明的有用信息——比如它是 #private 成员,还是 static,或者方法的名字是什么。让我们重写 loggedMethod 来利用这些信息,并打印出被装饰方法的名字。

🌐 We didn’t mention it yet, but loggedMethod was defined with a second parameter. It’s called a “context object”, and it has some useful information about how the decorated method was declared - like whether it was a #private member, or static, or what the name of the method was. Let’s rewrite loggedMethod to take advantage of that and print out the name of the method that was decorated.

ts
function loggedMethod(originalMethod: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
function replacementMethod(this: any, ...args: any[]) {
console.log(`LOG: Entering method '${methodName}'.`)
const result = originalMethod.call(this, ...args);
console.log(`LOG: Exiting method '${methodName}'.`)
return result;
}
return replacementMethod;
}

我们现在正在使用 context 参数——并且它是在 loggedMethod 中第一个类型比 anyany[] 更严格的东西。TypeScript 提供了一种名为 ClassMethodDecoratorContext 的类型,用于模拟方法装饰器所接受的上下文对象。

🌐 We’re now using the context parameter - and that it’s the first thing in loggedMethod that has a type stricter than any and any[]. TypeScript provides a type called ClassMethodDecoratorContext that models the context object that method decorators take.

除了元数据之外,方法的上下文对象还有一个叫做 addInitializer 的有用功能。它是一种在构造函数开始阶段进行钩子的方式(如果我们处理的是 static,则是在类本身初始化阶段钩子)。

🌐 Apart from metadata, the context object for methods also has a useful function called addInitializer. It’s a way to hook into the beginning of the constructor (or the initialization of the class itself if we’re working with statics).

举个例子——在 JavaScript 中,通常会写如下模式的代码:

🌐 As an example - in JavaScript, it’s common to write something like the following pattern:

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
this.greet = this.greet.bind(this);
}
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}

或者,可以将 greet 声明为一个属性,并将其初始化为箭头函数。

🌐 Alternatively, greet might be declared as a property initialized to an arrow function.

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
greet = () => {
console.log(`Hello, my name is ${this.name}.`);
};
}

编写此代码是为了确保如果 greet 作为独立函数调用或作为回调传递时,this 不会被重新绑定。

🌐 This code is written to ensure that this isn’t re-bound if greet is called as a stand-alone function or passed as a callback.

ts
const greet = new Person("Ray").greet;
// We don't want this to fail!
greet();

我们可以编写一个装饰器,使用 addInitializer 在构造函数中为我们调用 bind

🌐 We can write a decorator that uses addInitializer to call bind in the constructor for us.

ts
function bound(originalMethod: any, context: ClassMethodDecoratorContext) {
const methodName = context.name;
if (context.private) {
throw new Error(`'bound' cannot decorate private properties like ${methodName as string}.`);
}
context.addInitializer(function () {
this[methodName] = this[methodName].bind(this);
});
}

bound 不会返回任何内容——所以当它装饰一个方法时,会保持原方法不变。相反,它会在其他任何字段初始化之前添加逻辑。

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
@bound
@loggedMethod
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const p = new Person("Ray");
const greet = p.greet;
// Works!
greet();

注意我们叠加了两个装饰器——@bound@loggedMethod。 这些装饰器按“反向顺序”运行。 也就是说,@loggedMethod装饰的是原始方法greet,而@bound装饰的是@loggedMethod的结果。 在这个例子中,这无关紧要——但如果你的装饰器有副作用或期望特定顺序的话,就可能会有影响。

🌐 Notice that we stacked two decorators - @bound and @loggedMethod. These decorations run in “reverse order”. That is, @loggedMethod decorates the original method greet, and @bound decorates the result of @loggedMethod. In this example, it doesn’t matter - but it could if your decorators have side-effects or expect a certain order.

同样值得注意的是——如果你在风格上更倾向这样,也可以把这些装饰器写在同一行。

🌐 Also worth noting - if you’d prefer stylistically, you can put these decorators on the same line.

ts
@bound @loggedMethod greet() {
console.log(`Hello, my name is ${this.name}.`);
}

有一点可能不太明显,那就是我们甚至可以创建返回装饰器函数的函数。这样就可以稍微定制一下最终的装饰器。如果我们愿意,我们本可以让 loggedMethod 返回一个装饰器,并自定义它记录消息的方式。

🌐 Something that might not be obvious is that we can even make functions that return decorator functions. That makes it possible to customize the final decorator just a little. If we wanted, we could have made loggedMethod return a decorator and customize how it logs its messages.

ts
function loggedMethod(headMessage = "LOG:") {
return function actualDecorator(originalMethod: any, context: ClassMethodDecoratorContext) {
const methodName = String(context.name);
function replacementMethod(this: any, ...args: any[]) {
console.log(`${headMessage} Entering method '${methodName}'.`)
const result = originalMethod.call(this, ...args);
console.log(`${headMessage} Exiting method '${methodName}'.`)
return result;
}
return replacementMethod;
}
}

如果我们那样做,就必须在使用 loggedMethod 作为装饰器之前调用它。然后我们可以传入任何字符串作为日志消息输出到控制台时的前缀。

🌐 If we did that, we’d have to call loggedMethod before using it as a decorator. We could then pass in any string as the prefix for messages that get logged to the console.

ts
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
@loggedMethod("⚠️")
greet() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const p = new Person("Ray");
p.greet();
// Output:
//
// ⚠️ Entering method 'greet'.
// Hello, my name is Ray.
// ⚠️ Exiting method 'greet'.

装饰器不仅可以用于方法! 它们可以用于属性/字段、getter、setter 和自动访问器。 甚至类本身也可以被装饰,用于子类化和注册等功能。

🌐 Decorators can be used on more than just methods! They can be used on properties/fields, getters, setters, and auto-accessors. Even classes themselves can be decorated for things like subclassing and registration.

要深入了解装饰器,你可以阅读 Axel Rauschmayer 的详细总结

🌐 To learn more about decorators in-depth, you can read up on Axel Rauschmayer’s extensive summary.

有关所涉及更改的更多信息,你可以查看原始拉取请求

🌐 For more information about the changes involved, you can view the original pull request.

与实验性旧式装饰器的区别

🌐 Differences with Experimental Legacy Decorators

如果你已经使用 TypeScript 一段时间了,你可能知道它多年来一直支持“实验性”的装饰器。虽然这些实验性装饰器非常有用,但它们基于的是装饰器提案的一个早期版本,并且始终需要一个名为 --experimentalDecorators 的编译器选项来启用。任何在没有启用该选项的情况下尝试在 TypeScript 中使用装饰器的操作,都会提示错误信息。

🌐 If you’ve been using TypeScript for a while, you might be aware of the fact that it’s had support for “experimental” decorators for years. While these experimental decorators have been incredibly useful, they modeled a much older version of the decorators proposal, and always required an opt-in compiler flag called --experimentalDecorators. Any attempt to use decorators in TypeScript without this flag used to prompt an error message.

--experimentalDecorators 在可预见的将来将继续存在;然而,没有该标志时,装饰器现在对所有新代码都是有效的语法。在 --experimentalDecorators 之外,它们将以不同的方式进行类型检查和输出。类型检查规则和输出足够不同,以至于虽然可以编写装饰器以同时支持旧版和新版的装饰器行为,但任何现有的装饰器函数都不太可能做到这一点。

这个新的装饰器提案与 --emitDecoratorMetadata 不兼容,并且不允许装饰参数。未来的 ECMAScript 提案可能有助于弥合这一差距。

🌐 This new decorators proposal is not compatible with --emitDecoratorMetadata, and it does not allow decorating parameters. Future ECMAScript proposals may be able to help bridge that gap.

最后一点:除了允许将装饰器放在 export 关键字之前之外,关于装饰器的提案现在还提供了在 exportexport default 之后放置装饰器的选项。唯一的例外是,不允许混合使用这两种风格。

🌐 On a final note: in addition to allowing decorators to be placed before the export keyword, the proposal for decorators now provides the option of placing decorators after export or export default. The only exception is that mixing the two styles is not allowed.

js
// ✅ allowed
@register export default class Foo {
// ...
}
// ✅ also allowed
export default @register class Bar {
// ...
}
// ❌ error - before *and* after is not allowed
@before export @after class Bar {
// ...
}

编写类型良好的装饰器

🌐 Writing Well-Typed Decorators

上面 loggedMethodbound 的装饰器示例故意很简单,并省略了很多关于类型的细节。

🌐 The loggedMethod and bound decorator examples above are intentionally simple and omit lots of details about types.

类型装饰器可能相当复杂。 例如,上面 loggedMethod 的一个类型良好的版本可能看起来像这样:

🌐 Typing decorators can be fairly complex. For example, a well-typed version of loggedMethod from above might look something like this:

ts
function loggedMethod<This, Args extends any[], Return>(
target: (this: This, ...args: Args) => Return,
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>
) {
const methodName = String(context.name);
function replacementMethod(this: This, ...args: Args): Return {
console.log(`LOG: Entering method '${methodName}'.`)
const result = target.call(this, ...args);
console.log(`LOG: Exiting method '${methodName}'.`)
return result;
}
return replacementMethod;
}

我们必须分别对 this 的类型、原方法的参数和返回类型建模,使用类型参数 ThisArgsReturn

🌐 We had to separately model out the type of this, the parameters, and the return type of the original method, using the type parameters This, Args, and Return.

你定义的装饰器函数有多复杂,取决于你想要保证的内容。记住,装饰器的使用次数通常会多于它们被编写的次数,因此一个类型明确的版本通常是更可取的——但显然这会影响可读性,所以尽量保持简单。

🌐 Exactly how complex your decorators functions are defined depends on what you want to guarantee. Just keep in mind, your decorators will be used more than they’re written, so a well-typed version will usually be preferable - but there’s clearly a trade-off with readability, so try to keep things simple.

关于编写装饰器的更多文档将会在未来提供——但这篇文章应该已经对装饰器的机制提供了相当详细的说明。

🌐 More documentation on writing decorators will be available in the future - but this post should have a good amount of detail for the mechanics of decorators.

const 类型参数

🌐 const Type Parameters

在推断对象的类型时,TypeScript 通常会选择一个通用类型。 例如,在这种情况下,names 的推断类型是 string[]

🌐 When inferring the type of an object, TypeScript will usually choose a type that’s meant to be general. For example, in this case, the inferred type of names is string[]:

ts
type HasNames = { names: readonly string[] };
function getNamesExactly<T extends HasNames>(arg: T): T["names"] {
return arg.names;
}
// Inferred type: string[]
const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"]});

通常,这样做的目的是为了便于后续修改。

🌐 Usually the intent of this is to enable mutation down the line.

然而,根据 getNamesExactly 的具体功能以及它的预期使用方式,通常情况下可能需要一个更具体的类型。

🌐 However, depending on what exactly getNamesExactly does and how it’s intended to be used, it can often be the case that a more-specific type is desired.

到目前为止,API 作者通常必须建议在某些地方添加 as const 以实现所需的推断:

🌐 Up until now, API authors have typically had to recommend adding as const in certain places to achieve the desired inference:

ts
// The type we wanted:
// readonly ["Alice", "Bob", "Eve"]
// The type we got:
// string[]
const names1 = getNamesExactly({ names: ["Alice", "Bob", "Eve"]});
// Correctly gets what we wanted:
// readonly ["Alice", "Bob", "Eve"]
const names2 = getNamesExactly({ names: ["Alice", "Bob", "Eve"]} as const);

这可能会很麻烦且容易忘记。在 TypeScript 5.0 中,你现在可以在类型参数声明中添加 const 修饰符,从而使 const 式的推断成为默认行为:

🌐 This can be cumbersome and easy to forget. In TypeScript 5.0, you can now add a const modifier to a type parameter declaration to cause const-like inference to be the default:

ts
type HasNames = { names: readonly string[] };
function getNamesExactly<const T extends HasNames>(arg: T): T["names"] {
// ^^^^^
return arg.names;
}
// Inferred type: readonly ["Alice", "Bob", "Eve"]
// Note: Didn't need to write 'as const' here
const names = getNamesExactly({ names: ["Alice", "Bob", "Eve"] });

请注意,const 修饰符并不会拒绝可变值,也不要求不可变约束。使用可变类型约束可能会得到令人意外的结果。例如:

🌐 Note that the const modifier doesn’t reject mutable values, and doesn’t require immutable constraints. Using a mutable type constraint might give surprising results. For example:

ts
declare function fnBad<const T extends string[]>(args: T): void;
// 'T' is still 'string[]' since 'readonly ["a", "b", "c"]' is not assignable to 'string[]'
fnBad(["a", "b" ,"c"]);

这里,T 推断出的候选类型是 readonly ["a", "b", "c"],并且在需要可变数组的地方不能使用 readonly 数组。 在这种情况下,类型推断会回退到约束,将数组视为 string[],并且调用仍然可以成功进行。

🌐 Here, the inferred candidate for T is readonly ["a", "b", "c"], and a readonly array can’t be used where a mutable one is needed. In this case, inference falls back to the constraint, the array is treated as string[], and the call still proceeds successfully.

对该函数更好的定义应该使用 readonly string[]

🌐 A better definition of this function should use readonly string[]:

ts
declare function fnGood<const T extends readonly string[]>(args: T): void;
// T is readonly ["a", "b", "c"]
fnGood(["a", "b" ,"c"]);

同样,请记住,const 修饰符仅影响在调用中编写的对象、数组和基本表达式的推断,因此那些无法(或不可能)使用 as const 修改的参数,其行为不会发生任何变化:

🌐 Similarly, remember to keep in mind that the const modifier only affects inference of object, array and primitive expressions that were written within the call, so arguments which wouldn’t (or couldn’t) be modified with as const won’t see any change in behavior:

ts
declare function fnGood<const T extends readonly string[]>(args: T): void;
const arr = ["a", "b" ,"c"];
// 'T' is still 'string[]'-- the 'const' modifier has no effect here
fnGood(arr);

查看拉取请求 以及 (第一个第二个) 相关问题了解更多详情。

extends 中支持多个配置文件

🌐 Supporting Multiple Configuration Files in extends

在管理多个项目时,拥有一个可以被其他 tsconfig.json 文件扩展的“基础”配置文件可能会很有帮助。这就是为什么 TypeScript 支持 extends 字段来从 compilerOptions 复制字段的原因。

🌐 When managing multiple projects, it can be helpful to have a “base” configuration file that other tsconfig.json files can extend from. That’s why TypeScript supports an extends field for copying over fields from compilerOptions.

jsonc
// packages/front-end/src/tsconfig.json
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "../lib",
// ...
}
}

然而,也有一些场景你可能希望从多个配置文件进行扩展。例如,想象一下使用 一个发布到 npm 的 TypeScript 基础配置文件。如果你希望所有项目也使用 npm 上 @tsconfig/strictest 包中的选项,那么有一个简单的解决方案:让 tsconfig.base.json 扩展自 @tsconfig/strictest

🌐 However, there are scenarios where you might want to extend from multiple configuration files. For example, imagine using a TypeScript base configuration file shipped to npm. If you want all your projects to also use the options from the @tsconfig/strictest package on npm, then there’s a simple solution: have tsconfig.base.json extend from @tsconfig/strictest:

jsonc
// tsconfig.base.json
{
"extends": "@tsconfig/strictest/tsconfig.json",
"compilerOptions": {
// ...
}
}

这种方法在一定程度上有效。如果你有任何不想使用 @tsconfig/strictest 的项目,它们必须要么手动禁用这些选项,要么创建一个不继承自 @tsconfig/strictesttsconfig.base.json 的单独版本。

🌐 This works to a point. If you have any projects that don’t want to use @tsconfig/strictest, they have to either manually disable the options, or create a separate version of tsconfig.base.json that doesn’t extend from @tsconfig/strictest.

为了在此提供更多灵活性,Typescript 5.0 现在允许 extends 字段接受多个条目。例如,在这个配置文件中:

🌐 To give some more flexibility here, Typescript 5.0 now allows the extends field to take multiple entries. For example, in this configuration file:

jsonc
{
"extends": ["a", "b", "c"],
"compilerOptions": {
// ...
}
}

写这个有点像直接扩展 c,其中 c 扩展 b,而 b 扩展 a。如果有字段“冲突”,后面的条目胜出。

🌐 Writing this is kind of like extending c directly, where c extends b, and b extends a. If any fields “conflict”, the latter entry wins.

所以在下面的例子中,最终的 tsconfig.json 中同时启用了 strictNullChecksnoImplicitAny

🌐 So in the following example, both strictNullChecks and noImplicitAny are enabled in the final tsconfig.json.

jsonc
// tsconfig1.json
{
"compilerOptions": {
"strictNullChecks": true
}
}
// tsconfig2.json
{
"compilerOptions": {
"noImplicitAny": true
}
}
// tsconfig.json
{
"extends": ["./tsconfig1.json", "./tsconfig2.json"],
"files": ["./index.ts"]
}

再例如,我们可以按以下方式重写原始示例。

🌐 As another example, we can rewrite our original example in the following way.

jsonc
// packages/front-end/src/tsconfig.json
{
"extends": ["@tsconfig/strictest/tsconfig.json", "../../../tsconfig.base.json"],
"compilerOptions": {
"outDir": "../lib",
// ...
}
}

欲了解更多详情,请阅读原始拉取请求

🌐 For more details, read more on the original pull request.

所有 enum 都是联合 enum

🌐 All enums Are Union enums

TypeScript 最初引入枚举时,它们只不过是一组具有相同类型的数字常量。

🌐 When TypeScript originally introduced enums, they were nothing more than a set of numeric constants with the same type.

ts
enum E {
Foo = 10,
Bar = 20,
}

E.FooE.Bar 唯一特别的地方在于它们可以赋值给任何期望 E 类型的东西。除此之外,它们基本上就是 number

🌐 The only thing special about E.Foo and E.Bar was that they were assignable to anything expecting the type E. Other than that, they were pretty much just numbers.

ts
function takeValue(e: E) {}
takeValue(E.Foo); // works
takeValue(123); // error!

直到 TypeScript 2.0 引入枚举字面量类型,枚举才变得更加特殊。枚举字面量类型为每个枚举成员赋予了自己的类型,并将枚举本身转换为每个成员类型的联合。它们还允许我们仅引用枚举的一部分类型,并缩小这些类型的范围。

🌐 It wasn’t until TypeScript 2.0 introduced enum literal types that enums got a bit more special. Enum literal types gave each enum member its own type, and turned the enum itself into a union of each member type. They also allowed us to refer to only a subset of the types of an enum, and to narrow away those types.

ts
// Color is like a union of Red | Orange | Yellow | Green | Blue | Violet
enum Color {
Red, Orange, Yellow, Green, Blue, /* Indigo, */ Violet
}
// Each enum member has its own type that we can refer to!
type PrimaryColor = Color.Red | Color.Green | Color.Blue;
function isPrimaryColor(c: Color): c is PrimaryColor {
// Narrowing literal types can catch bugs.
// TypeScript will error here because
// we'll end up comparing 'Color.Red' to 'Color.Green'.
// We meant to use ||, but accidentally wrote &&.
return c === Color.Red && c === Color.Green && c === Color.Blue;
}

给每个枚举成员分配自己的类型的一个问题是,这些类型在某种程度上与成员的实际值相关联。在某些情况下,无法计算该值——例如,一个枚举成员可能是通过函数调用来初始化的。

🌐 One issue with giving each enum member its own type was that those types were in some part associated with the actual value of the member. In some cases it’s not possible to compute that value - for instance, an enum member could be initialized by a function call.

ts
enum E {
Blah = Math.random()
}

每当 TypeScript 遇到这些问题时,它会悄悄地退回并使用旧的枚举策略。这意味着放弃联合类型和字面量类型的所有优势。

🌐 Whenever TypeScript ran into these issues, it would quietly back out and use the old enum strategy. That meant giving up all the advantages of unions and literal types.

TypeScript 5.0 通过为每个计算成员创建唯一类型,将所有枚举管理为联合枚举。这意味着现在所有枚举都可以被缩小,并且其成员也可以作为类型引用。

🌐 TypeScript 5.0 manages to make all enums into union enums by creating a unique type for each computed member. That means that all enums can now be narrowed and have their members referenced as types as well.

有关此更改的更多详细信息,你可以在 GitHub 上查看具体内容

🌐 For more details on this change, you can read the specifics on GitHub.

--moduleResolution bundler

TypeScript 4.7 为其 --module--moduleResolution 设置引入了 node16nodenext 选项。 这些选项的目的是更好地模拟 Node.js 中 ECMAScript 模块的精确查找规则;然而,这种模式有许多其他工具并不真正强制的限制。

🌐 TypeScript 4.7 introduced the node16 and nodenext options for its --module and --moduleResolution settings. The intent of these options was to better model the precise lookup rules for ECMAScript modules in Node.js; however, this mode has many restrictions that other tools don’t really enforce.

例如,在 Node.js 的 ECMAScript 模块中,任何相对导入都需要包含文件扩展名。

🌐 For example, in an ECMAScript module in Node.js, any relative import needs to include a file extension.

js
// entry.mjs
import * as utils from "./utils"; // ❌ wrong - we need to include the file extension.
import * as utils from "./utils.mjs"; // ✅ works

在 Node.js 和浏览器中,这有一些特定的原因——它使文件查询更快,并且对简单的文件服务器更有效。但对于使用打包工具的许多开发者来说,node16/nodenext 设置很繁琐,因为打包工具没有大多数这些限制。在某些方面,node 解析模式对使用打包工具的开发者来说更好。

🌐 There are certain reasons for this in Node.js and the browser - it makes file lookups faster and works better for naive file servers. But for many developers using tools like bundlers, the node16/nodenext settings were cumbersome because bundlers don’t have most of these restrictions. In some ways, the node resolution mode was better for anyone using a bundler.

但在某些方面,原始的 node 解析模式已经过时。大多数现代打包工具在 Node.js 中使用 ECMAScript 模块和 CommonJS 查找规则的融合。例如,无扩展名导入可以像在 CommonJS 中一样正常工作,但在查看一个包的 export 条件 时,它们会像在 ECMAScript 文件中一样优先考虑 import 条件。

🌐 But in some ways, the original node resolution mode was already out of date. Most modern bundlers use a fusion of the ECMAScript module and CommonJS lookup rules in Node.js. For example, extensionless imports work just fine just like in CommonJS, but when looking through the export conditions of a package, they’ll prefer an import condition just like in an ECMAScript file.

为了模拟打包工具的工作方式,TypeScript 现在引入了一种新策略:--moduleResolution bundler

🌐 To model how bundlers work, TypeScript now introduces a new strategy: --moduleResolution bundler.

jsonc
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "bundler"
}
}

如果你使用的是像 Vite、esbuild、swc、Webpack、Parcel 等现代打包工具,它们实现了混合查找策略,那么新的 bundler 选项应该非常适合你。

🌐 If you are using a modern bundler like Vite, esbuild, swc, Webpack, Parcel, and others that implement a hybrid lookup strategy, the new bundler option should be a good fit for you.

另一方面,如果你正在编写一个打算发布到 npm 的库,使用 bundler 选项可能会隐藏那些对不使用打包工具的用户可能产生的兼容性问题。因此,在这些情况下,使用 node16nodenext 的解析选项可能是更好的选择。

🌐 On the other hand, if you’re writing a library that’s meant to be published on npm, using the bundler option can hide compatibility issues that may arise for your users who aren’t using a bundler. So in these cases, using the node16 or nodenext resolution options is likely to be a better path.

要阅读更多关于 --moduleResolution bundler 的内容,请查看实现该功能的拉取请求

🌐 To read more on --moduleResolution bundler, take a look at the implementing pull request.

解析自定义标志

🌐 Resolution Customization Flags

JavaScript 工具现在可以模拟“混合”解析规则,就像我们上面描述的 bundler 模式一样。由于不同的工具在支持上可能略有差异,TypeScript 5.0 提供了启用或禁用一些功能的方法,这些功能可能在你的配置中可用,也可能不可用。

🌐 JavaScript tooling may now model “hybrid” resolution rules, like in the bundler mode we described above. Because tools may differ in their support slightly, TypeScript 5.0 provides ways to enable or disable a few features that may or may not work with your configuration.

allowImportingTsExtensions

--allowImportingTsExtensions 允许 TypeScript 文件使用 TypeScript 特有的扩展名(如 .ts.mts.tsx)相互导入。

只有在启用 --noEmit--emitDeclarationOnly 时才允许使用此标志,因为在 JavaScript 输出文件中这些导入路径在运行时无法解析。这里的期望是你的解析器(例如你的打包工具、运行时或其他工具)能够使 .ts 文件之间的这些导入正常工作。

🌐 This flag is only allowed when --noEmit or --emitDeclarationOnly is enabled, since these import paths would not be resolvable at runtime in JavaScript output files. The expectation here is that your resolver (e.g. your bundler, a runtime, or some other tool) is going to make these imports between .ts files work.

resolvePackageJsonExports

--resolvePackageJsonExports 会强制 TypeScript 在从 node_modules 中的某个包读取内容时,查阅 package.json 文件的 exports 字段

--moduleResolutionnode16nodenextbundler 选项下,此选项默认为 true

🌐 This option defaults to true under the node16, nodenext, and bundler options for --moduleResolution.

resolvePackageJsonImports

--resolvePackageJsonImports 强制 TypeScript 在执行从其祖级目录包含 package.json 的文件中以 # 开头的查找时,参考 package.json 文件的 imports 字段

--moduleResolutionnode16nodenextbundler 选项下,此选项默认为 true

🌐 This option defaults to true under the node16, nodenext, and bundler options for --moduleResolution.

allowArbitraryExtensions

在 TypeScript 5.0 中,当导入路径以不是已知 JavaScript 或 TypeScript 文件扩展名的扩展名结尾时,编译器会查找该路径对应的声明文件,格式为 {file basename}.d.{extension}.ts。 例如,如果你在打包项目中使用 CSS 加载器,你可能希望为那些样式表编写(或生成)声明文件:

🌐 In TypeScript 5.0, when an import path ends in an extension that isn’t a known JavaScript or TypeScript file extension, the compiler will look for a declaration file for that path in the form of {file basename}.d.{extension}.ts. For example, if you are using a CSS loader in a bundler project, you might want to write (or generate) declaration files for those stylesheets:

css
/* app.css */
.cookie-banner {
display: none;
}
ts
// app.d.css.ts
declare const css: {
cookieBanner: string;
};
export default css;
ts
// App.tsx
import styles from "./app.css";
styles.cookieBanner; // string

默认情况下,这个导入会抛出一个错误,提示你 TypeScript 不理解这种文件类型,并且你的运行时可能不支持导入它。但是,如果你已经配置了运行时或打包工具来处理它,你可以使用新的 --allowArbitraryExtensions 编译器选项来抑制错误。

🌐 By default, this import will raise an error to let you know that TypeScript doesn’t understand this file type and your runtime might not support importing it. But if you’ve configured your runtime or bundler to handle it, you can suppress the error with the new --allowArbitraryExtensions compiler option.

请注意,从历史上看,通过添加名为 app.css.d.ts 的声明文件而不是 app.d.css.ts,通常可以实现类似的效果——然而,这只是通过 Node 对 CommonJS 的 require 解析规则实现的。严格来说,前者被解释为一个名为 app.css.js 的 JavaScript 文件的声明文件。由于在 Node 的 ESM 支持中,相对文件导入需要包含扩展名,因此在 --moduleResolution node16nodenext 下的 ESM 文件中,我们的示例会在 TypeScript 中报错。

🌐 Note that historically, a similar effect has often been achievable by adding a declaration file named app.css.d.ts instead of app.d.css.ts - however, this just worked through Node’s require resolution rules for CommonJS. Strictly speaking, the former is interpreted as a declaration file for a JavaScript file named app.css.js. Because relative files imports need to include extensions in Node’s ESM support, TypeScript would error on our example in an ESM file under --moduleResolution node16 or nodenext.

欲了解更多信息,请阅读此功能的提案以及其对应的拉取请求

🌐 For more information, read up the proposal for this feature and its corresponding pull request.

customConditions

--customConditions 接受一个额外 条件 列表,当 TypeScript 从 package.jsonexportsimports 字段解析时,这些条件应该成功。这些条件会被添加到解析器默认使用的任何现有条件中。

例如,当在 tsconfig.json 中如此设置此字段时:

🌐 For example, when this field is set in a tsconfig.json as so:

jsonc
{
"compilerOptions": {
"target": "es2022",
"moduleResolution": "bundler",
"customConditions": ["my-condition"]
}
}

每当在 package.json 中引用 exportsimports 字段时,TypeScript 会考虑称为 my-condition 的条件。

🌐 Any time an exports or imports field is referenced in package.json, TypeScript will consider conditions called my-condition.

所以当从包含以下 package.json 的包导入时

🌐 So when importing from a package with the following package.json

jsonc
{
// ...
"exports": {
".": {
"my-condition": "./foo.mjs",
"node": "./bar.mjs",
"import": "./baz.mjs",
"require": "./biz.mjs"
}
}
}

TypeScript 会尝试查找与 foo.mjs 对应的文件。

🌐 TypeScript will try to look for files corresponding to foo.mjs.

此字段仅在 --moduleResolutionnode16nodenextbundler 选项下有效

🌐 This field is only valid under the node16, nodenext, and bundler options for --moduleResolution

--verbatimModuleSyntax

默认情况下,TypeScript 会执行一种称为导入省略的操作。基本上,如果你写了类似这样的内容

🌐 By default, TypeScript does something called import elision. Basically, if you write something like

ts
import { Car } from "./car";
export function drive(car: Car) {
// ...
}

TypeScript 会检测到你只是在使用类型的导入,并会完全删除该导入。 你的输出 JavaScript 可能看起来像这样:

🌐 TypeScript detects that you’re only using an import for types and drops the import entirely. Your output JavaScript might look something like this:

js
export function drive(car) {
// ...
}

大多数情况下这是好的,因为如果 Car 不是从 ./car 导出的值,我们就会遇到运行时错误。

🌐 Most of the time this is good, because if Car isn’t a value that’s exported from ./car, we’ll get a runtime error.

但对于某些边缘情况,它确实增加了一层复杂性。例如,请注意没有像 import "./car"; 这样的语句——导入被完全删除了。对于有副作用的模块或没有副作用的模块来说,这实际上是有区别的。

🌐 But it does add a layer of complexity for certain edge cases. For example, notice there’s no statement like import "./car"; - the import was dropped entirely. That actually makes a difference for modules that have side-effects or not.

TypeScript 对 JavaScript 的输出策略还有另外几层复杂性——导入消除并不总是仅由导入的使用方式决定——它通常还会参考值是如何声明的。 所以像下面这样的代码并不总是很清楚

🌐 TypeScript’s emit strategy for JavaScript also has another few layers of complexity - import elision isn’t always just driven by how an import is used - it often consults how a value is declared as well. So it’s not always clear whether code like the following

ts
export { Car } from "./car";

应该被保留或丢弃。 如果 Car 是用类似 class 的东西声明的,那么它可以在生成的 JavaScript 文件中保留。 但如果 Car 仅被声明为 type 别名或 interface,那么 JavaScript 文件根本不应该导出 Car

🌐 should be preserved or dropped. If Car is declared with something like a class, then it can be preserved in the resulting JavaScript file. But if Car is only declared as a type alias or interface, then the JavaScript file shouldn’t export Car at all.

虽然 TypeScript 可能能够根据来自各个文件的信息做出这些触发决定,但并非每个编译器都可以。

🌐 While TypeScript might be able to make these emit decisions based on information from across files, not every compiler can.

导入和导出上的 type 修饰符在这些情况下有一定帮助。我们可以明确指出某个导入或导出仅用于类型分析,并且在 JavaScript 文件中可以通过使用 type 修饰符将其完全省略。

🌐 The type modifier on imports and exports helps with these situations a bit. We can make it explicit whether an import or export is only being used for type analysis, and can be dropped entirely in JavaScript files by using the type modifier.

ts
// This statement can be dropped entirely in JS output
import type * as car from "./car";
// The named import/export 'Car' can be dropped in JS output
import { type Car } from "./car";
export { type Car } from "./car";

type 修饰符本身并不是特别有用——默认情况下,模块省略仍然会去掉导入,而且没有任何东西强制你区分 type 和普通的导入与导出。因此 TypeScript 提供了 --importsNotUsedAsValues 标志以确保你使用 type 修饰符,--preserveValueImports 用于防止某些模块省略行为,--isolatedModules 确保你的 TypeScript 代码可以在不同的编译器中正常工作。不幸的是,理解这三个标志的具体细节比较困难,而且仍然存在一些意外行为的边缘情况。

TypeScript 5.0 引入了一个名为 --verbatimModuleSyntax 的新选项来简化这种情况。规则更简单——任何没有 type 修饰符的导入或导出都会保留下来。任何使用 type 修饰符的内容都会被完全移除。

🌐 TypeScript 5.0 introduces a new option called --verbatimModuleSyntax to simplify the situation. The rules are much simpler - any imports or exports without a type modifier are left around. Anything that uses the type modifier is dropped entirely.

ts
// Erased away entirely.
import type { A } from "a";
// Rewritten to 'import { b } from "bcd";'
import { b, type c, type d } from "bcd";
// Rewritten to 'import {} from "xyz";'
import { type xyz } from "xyz";

有了这个新选项,所见即所得。

🌐 With this new option, what you see is what you get.

不过在模块互操作方面,这确实有一些影响。在启用此标志时,当你的设置或文件扩展名暗示了不同的模块系统时,ECMAScript importexport 不会被重写为 require 调用。取而代之的,你会收到一个错误。如果你需要生成使用 requiremodule.exports 的代码,你必须使用早于 ES2015 的 TypeScript 模块语法:

🌐 That does have some implications when it comes to module interop though. Under this flag, ECMAScript imports and exports won’t be rewritten to require calls when your settings or file extension implied a different module system. Instead, you’ll get an error. If you need to emit code that uses require and module.exports, you’ll have to use TypeScript’s module syntax that predates ES2015:

输入 TypeScript 输出 JavaScript
ts
import foo = require("foo");
js
const foo = require("foo");
ts
function foo() {}
function bar() {}
function baz() {}
export = {
foo,
bar,
baz
};
js
function foo() {}
function bar() {}
function baz() {}
module.exports = {
foo,
bar,
baz
};

虽然这是一个限制,但它确实有助于让一些问题更加明显。例如,非常常见的情况是忘记在 --module node16 下设置 package.jsontype 字段。因此,开发者可能会在不自觉的情况下开始编写 CommonJS 模块而不是 ES 模块,从而导致意外的查找规则和 JavaScript 输出。这个新标志确保你对所使用的文件类型是有意选择的,因为语法是刻意不同的。

🌐 While this is a limitation, it does help make some issues more obvious. For example, it’s very common to forget to set the type field in package.json under --module node16. As a result, developers would start writing CommonJS modules instead of ES modules without realizing it, giving surprising lookup rules and JavaScript output. This new flag ensures that you’re intentional about the file type you’re using because the syntax is intentionally different.

因为 --verbatimModuleSyntax 提供的情况比 --importsNotUsedAsValues--preserveValueImports 更一致,所以这两个现有的标记将被淘汰,以支持 --verbatimModuleSyntax

🌐 Because --verbatimModuleSyntax provides a more consistent story than --importsNotUsedAsValues and --preserveValueImports, those two existing flags are being deprecated in its favor.

欲了解更多详情,请阅读[原始拉取请求]https://github.com/microsoft/TypeScript/pull/52203其提案问题

🌐 For more details, read up on [the original pull request]https://github.com/microsoft/TypeScript/pull/52203 and its proposal issue.

支持 export type *

🌐 Support for export type *

当 TypeScript 3.8 引入仅类型导入时,这种新语法不允许用于 export * from "module"export * as ns from "module" 的重新导出。TypeScript 5.0 添加了对这两种形式的支持:

🌐 When TypeScript 3.8 introduced type-only imports, the new syntax wasn’t allowed on export * from "module" or export * as ns from "module" re-exports. TypeScript 5.0 adds support for both of these forms:

ts
// models/vehicles.ts
export class Spaceship {
// ...
}
// models/index.ts
export type * as vehicles from "./vehicles";
// main.ts
import { vehicles } from "./models";
function takeASpaceship(s: vehicles.Spaceship) {
// ✅ ok - `vehicles` only used in a type position
}
function makeASpaceship() {
return new vehicles.Spaceship();
// ^^^^^^^^
// 'vehicles' cannot be used as a value because it was exported using 'export type'.
}

你可以在这里阅读更多关于实现的内容

🌐 You can read more about the implementation here.

@satisfies 在 JSDoc 中的支持

🌐 @satisfies Support in JSDoc

TypeScript 4.9 引入了 satisfies 操作符。它确保一个表达式的类型是兼容的,但不会影响类型本身。例如,我们来看以下代码:

🌐 TypeScript 4.9 introduced the satisfies operator. It made sure that the type of an expression was compatible, without affecting the type itself. For example, let’s take the following code:

ts
interface CompilerOptions {
strict?: boolean;
outDir?: string;
// ...
}
interface ConfigSettings {
compilerOptions?: CompilerOptions;
extends?: string | string[];
// ...
}
let myConfigSettings = {
compilerOptions: {
strict: true,
outDir: "../lib",
// ...
},
extends: [
"@tsconfig/strictest/tsconfig.json",
"../../../tsconfig.base.json"
],
} satisfies ConfigSettings;

在这里,TypeScript 知道 myConfigSettings.extends 是用数组声明的——因为虽然 satisfies 验证了我们对象的类型,但它并没有直接将其变成 CompilerOptions 并丢失信息。所以如果我们想对 extends 进行映射,这是可以的。

🌐 Here, TypeScript knows that myConfigSettings.extends was declared with an array - because while satisfies validated the type of our object, it didn’t bluntly change it to CompilerOptions and lose information. So if we want to map over extends, that’s fine.

ts
declare function resolveConfig(configPath: string): CompilerOptions;
let inheritedConfigs = myConfigSettings.extends.map(resolveConfig);

这对 TypeScript 用户很有帮助,但很多人使用 TypeScript 来通过 JSDoc 注释对他们的 JavaScript 代码进行类型检查。 这就是为什么 TypeScript 5.0 支持一个名为 @satisfies 的新 JSDoc 标签,它的作用完全相同。

🌐 This was helpful for TypeScript users, but plenty of people use TypeScript to type-check their JavaScript code using JSDoc annotations. That’s why TypeScript 5.0 is supporting a new JSDoc tag called @satisfies that does exactly the same thing.

/** @satisfies */ 可以捕捉类型不匹配:

js
// @ts-check
/**
* @typedef CompilerOptions
* @prop {boolean} [strict]
* @prop {string} [outDir]
*/
/**
* @satisfies {CompilerOptions}
*/
let myCompilerOptions = {
outdir: "../lib",
// ~~~~~~ oops! we meant outDir
};

但它将保留表达式的原始类型,使我们能够在以后的代码中更精确地使用我们的值。

🌐 But it will preserve the original type of our expressions, allowing us to use our values more precisely later on in our code.

js
// @ts-check
/**
* @typedef CompilerOptions
* @prop {boolean} [strict]
* @prop {string} [outDir]
*/
/**
* @typedef ConfigSettings
* @prop {CompilerOptions} [compilerOptions]
* @prop {string | string[]} [extends]
*/
/**
* @satisfies {ConfigSettings}
*/
let myConfigSettings = {
compilerOptions: {
strict: true,
outDir: "../lib",
},
extends: [
"@tsconfig/strictest/tsconfig.json",
"../../../tsconfig.base.json"
],
};
let inheritedConfigs = myConfigSettings.extends.map(resolveConfig);

/** @satisfies */ 也可以在任何带括号的表达式中使用。我们可以这样写 myCompilerOptions

ts
let myConfigSettings = /** @satisfies {ConfigSettings} */ ({
compilerOptions: {
strict: true,
outDir: "../lib",
},
extends: [
"@tsconfig/strictest/tsconfig.json",
"../../../tsconfig.base.json"
],
});

为什么? 嗯,当你深入到其他代码中,比如一个函数调用时,这通常更有意义。

🌐 Why? Well, it usually makes more sense when you’re deeper in some other code, like a function call.

js
compileCode(/** @satisfies {CompilerOptions} */ ({
// ...
}));

感谢 Oleksandr Tarasiuk 提供了这个功能 此功能

@overload 在 JSDoc 中的支持

🌐 @overload Support in JSDoc

在 TypeScript 中,你可以为函数指定重载。重载让我们能够说明一个函数可以用不同的参数调用,并可能返回不同的结果。它们可以限制调用者实际如何使用我们的函数,并优化他们将获得的返回结果。

🌐 In TypeScript, you can specify overloads for a function. Overloads give us a way to say that a function can be called with different arguments, and possibly return different results. They can restrict how callers can actually use our functions, and refine what results they’ll get back.

ts
// Our overloads:
function printValue(str: string): void;
function printValue(num: number, maxFractionDigits?: number): void;
// Our implementation:
function printValue(value: string | number, maximumFractionDigits?: number) {
if (typeof value === "number") {
const formatter = Intl.NumberFormat("en-US", {
maximumFractionDigits,
});
value = formatter.format(value);
}
console.log(value);
}

这里,我们说过 printValue 的第一个参数可以是 stringnumber。如果它接收 number,则可以传入第二个参数来确定我们可以打印多少小数位。

🌐 Here, we’ve said that printValue takes either a string or a number as its first argument. If it takes a number, it can take a second argument to determine how many fractional digits we can print.

TypeScript 5.0 现在允许使用新的 @overload 标签在 JSDoc 中声明重载。每个带有 @overload 标签的 JSDoc 注释都被视为对随后函数声明的一个独立重载。

🌐 TypeScript 5.0 now allows JSDoc to declare overloads with a new @overload tag. Each JSDoc comment with an @overload tag is treated as a distinct overload for the following function declaration.

js
// @ts-check
/**
* @overload
* @param {string} value
* @return {void}
*/
/**
* @overload
* @param {number} value
* @param {number} [maximumFractionDigits]
* @return {void}
*/
/**
* @param {string | number} value
* @param {number} [maximumFractionDigits]
*/
function printValue(value, maximumFractionDigits) {
if (typeof value === "number") {
const formatter = Intl.NumberFormat("en-US", {
maximumFractionDigits,
});
value = formatter.format(value);
}
console.log(value);
}

现在,无论我们是在 TypeScript 还是 JavaScript 文件中编写,TypeScript 都会让我们知道我们是否错误地调用了函数。

🌐 Now regardless of whether we’re writing in a TypeScript or JavaScript file, TypeScript can let us know if we’ve called our functions incorrectly.

ts
// all allowed
printValue("hello!");
printValue(123.45);
printValue(123.45, 2);
printValue("hello!", 123); // error!

这个新标签的实现要感谢Tomasz Lenarcik

🌐 This new tag was implemented thanks to Tomasz Lenarcik.

--build 下传递特定于 Emit 的标志

🌐 Passing Emit-Specific Flags Under --build

TypeScript 现在允许在 --build 模式下传递以下标志

🌐 TypeScript now allows the following flags to be passed under --build mode

  • --declaration
  • --emitDeclarationOnly
  • --declarationMap
  • --sourceMap
  • --inlineSourceMap

这使得在开发和生产构建过程中自定义构建的某些部分变得更加容易。

🌐 This makes it way easier to customize certain parts of a build where you might have different development and production builds.

例如,库的开发版本可能不需要生成声明文件,但生产版本则需要。项目可以将声明输出默认设置为关闭,然后只进行构建。

🌐 For example, a development build of a library might not need to produce declaration files, but a production build would. A project can configure declaration emit to be off by default and simply be built with

sh
tsc --build -p ./my-project-dir

一旦你完成了内部循环的迭代,“生产”版本就可以直接传递 --declaration 标志。

🌐 Once you’re done iterating in the inner loop, a “production” build can just pass the --declaration flag.

sh
tsc --build -p ./my-project-dir --declaration

有关此更改的更多信息,请点击这里

编辑器中不区分大小写的导入排序

🌐 Case-Insensitive Import Sorting in Editors

在像 Visual Studio 和 VS Code 这样的编辑器中,TypeScript 提供了用于组织和排序导入和导出的功能。然而,对于何时将列表视为“已排序”,常常会有不同的理解。

🌐 In editors like Visual Studio and VS Code, TypeScript powers the experience for organizing and sorting imports and exports. Often though, there can be different interpretations of when a list is “sorted”.

例如,以下导入列表是否已排序?

🌐 For example, is the following import list sorted?

ts
import {
Toggle,
freeze,
toBoolean,
} from "./utils";

答案可能会令人惊讶地是“视情况而定”。 如果我们在意大小写,那么这个列表显然没有排序。 字母 f 出现在 tT 之前。

🌐 The answer might surprisingly be “it depends”. If we don’t care about case-sensitivity, then this list is clearly not sorted. The letter f comes before both t and T.

但在大多数编程语言中,排序默认是比较字符串的字节值。 JavaScript 比较字符串的方式意味着 "Toggle" 总是排在 "freeze" 之前,因为根据 ASCII 字符编码,大写字母排在小写字母之前。 所以从这个角度来看,导入列表是已排序的。

🌐 But in most programming languages, sorting defaults to comparing the byte values of strings. The way JavaScript compares strings means that "Toggle" always comes before "freeze" because according to the ASCII character encoding, uppercase letters come before lowercase. So from that perspective, the import list is sorted.

TypeScript 之前认为导入列表是排序好的,因为它进行的是基本的区分大小写的排序。这可能会让那些更喜欢不区分大小写排序的开发者感到困扰,或者使用像 ESLint 这样的工具,而这些工具默认要求不区分大小写的排序。

🌐 TypeScript previously considered the import list to be sorted because it was doing a basic case-sensitive sort. This could be a point of frustration for developers who preferred a case-insensitive ordering, or who used tools like ESLint which require case-insensitive ordering by default.

TypeScript 现在默认会检测大小写敏感性。这意味着 TypeScript 和像 ESLint 这样的工具通常不会在如何最佳排序导入时互相“冲突”。

🌐 TypeScript now detects case sensitivity by default. This means that TypeScript and tools like ESLint typically won’t “fight” each other over how to best sort imports.

我们的团队也在尝试进一步的排序策略,你可以在这里阅读。 这些选项最终可能会由编辑器进行配置。 目前,它们仍然不稳定且处于实验阶段,你可以今天在 VS Code 中通过在 JSON 选项中使用 typescript.unstable 条目来选择使用它们。 下面是你可以尝试的所有选项(按默认值设置):

🌐 Our team has also been experimenting with further sorting strategies which you can read about here. These options may eventually be configurable by editors. For now, they are still unstable and experimental, and you can opt into them in VS Code today by using the typescript.unstable entry in your JSON options. Below are all of the options you can try out (set to their defaults):

jsonc
{
"typescript.unstable": {
// Should sorting be case-sensitive? Can be:
// - true
// - false
// - "auto" (auto-detect)
"organizeImportsIgnoreCase": "auto",
// Should sorting be "ordinal" and use code points or consider Unicode rules? Can be:
// - "ordinal"
// - "unicode"
"organizeImportsCollation": "ordinal",
// Under `"organizeImportsCollation": "unicode"`,
// what is the current locale? Can be:
// - [any other locale code]
// - "auto" (use the editor's locale)
"organizeImportsLocale": "en",
// Under `"organizeImportsCollation": "unicode"`,
// should upper-case letters or lower-case letters come first? Can be:
// - false (locale-specific)
// - "upper"
// - "lower"
"organizeImportsCaseFirst": false,
// Under `"organizeImportsCollation": "unicode"`,
// do runs of numbers get compared numerically (i.e. "a1" < "a2" < "a100")? Can be:
// - true
// - false
"organizeImportsNumericCollation": true,
// Under `"organizeImportsCollation": "unicode"`,
// do letters with accent marks/diacritics get sorted distinctly
// from their "base" letter (i.e. is é different from e)? Can be
// - true
// - false
"organizeImportsAccentCollation": true
},
"javascript.unstable": {
// same options valid here...
},
}

你可以阅读更多关于用于自动检测并指定不区分大小写的原作的详细信息,随后是更广泛选项集

🌐 You can read more details on the original work for auto-detecting and specifying case-insensitivity, followed by the the broader set of options.

完整的 switch/case 补全

🌐 Exhaustive switch/case Completions

在编写 switch 语句时,TypeScript 现在会检测被检查的值是否具有字面量类型。如果是,它将提供一个补全,搭建出每个未覆盖的 case

🌐 When writing a switch statement, TypeScript now detects when the value being checked has a literal type. If so, it will offer a completion that scaffolds out each uncovered case.

A set of case statements generated through auto-completion based on literal types.

你可以在 GitHub 上查看实现的具体细节

🌐 You can see specifics of the implementation on GitHub.

速度、内存和包大小优化

🌐 Speed, Memory, and Package Size Optimizations

TypeScript 5.0 在我们的代码结构、数据结构和算法实现方面包含了许多强大的变化。 这些变化意味着你的整体体验应该会更快——不仅仅是运行 TypeScript,还包括安装它。

🌐 TypeScript 5.0 contains lots of powerful changes across our code structure, our data structures, and algorithmic implementations. What these all mean is that your entire experience should be faster - not just running TypeScript, but even installing it.

以下是一些我们在速度和大小方面相对于 TypeScript 4.9 的有趣改进。

🌐 Here are a few interesting wins in speed and size that we’ve been able to capture relative to TypeScript 4.9.

场景 相对于 TS 4.9 的时间或大小
material-ui 构建时间 89%
TypeScript 编译器启动时间 89%
Playwright 构建时间 88%
TypeScript 编译器自构建时间 87%
Outlook Web 构建时间 82%
VS Code 构建时间 80%
typescript npm 包大小 59%
🌐 Scenario Time or Size Relative to TS 4.9
material-ui build time 89%
TypeScript Compiler startup time 89%
Playwright build time 88%
TypeScript Compiler self-build time 87%
Outlook Web build time 82%
VS Code build time 80%
typescript npm Package Size 59%

Chart of build/run times and package size of TypeScript 5.0 relative to TypeScript 4.9: material-ui docs build time: 89%; Playwright build time: 88%; tsc startup time: 87%; tsc build time: 87%; Outlook Web build time: 82%; VS Code build time: 80%; typescript Package Size: 59%

怎么做? 我们希望未来能提供更多细节,介绍一些值得注意的改进。 但我们不会让你为了那篇博客文章而等待。

🌐 How? There are a few notable improvements we’d like give more details on in the future. But we won’t make you wait for that blog post.

首先,我们最近将 TypeScript 从命名空间迁移到了模块,这使我们能够利用现代构建工具进行诸如作用域提升之类的优化。使用这些工具、重新审视我们的打包策略,并删除一些已弃用的代码,使 TypeScript 4.9 的 63.8 MB 包大小减少了约 26.4 MB。它还通过直接函数调用带来了显著的速度提升。

🌐 First off, we recently migrated TypeScript from namespaces to modules, allowing us to leverage modern build tooling that can perform optimizations like scope hoisting. Using this tooling, revisiting our packaging strategy, and removing some deprecated code has shaved off about 26.4 MB from TypeScript 4.9’s 63.8 MB package size. It also brought us a notable speed-up through direct function calls.

TypeScript 还为编译器内部的对象类型增加了更多的一致性,同时也精简了这些对象类型上存储的数据。这减少了多态和超多态的使用场景,同时抵消了为实现统一形状所必需的大部分内存消耗。

🌐 TypeScript also added more uniformity to internal object types within the compiler, and also slimmed the data stored on some of these object types as well. This reduced polymorphic and megamorphic use sites, while offsetting most of the necessary memory consumption that was necessary for uniform shapes.

我们在将信息序列化为字符串时也进行了一些缓存。类型显示可能作为错误报告、声明生成、代码补全等的一部分出现,这可能会变得相当昂贵。TypeScript 现在会缓存一些常用的机制,以便在这些操作中重复使用。

🌐 We’ve also performed some caching when serializing information to strings. Type display, which can happen as part of error reporting, declaration emit, code completions, and more, can end up being fairly expensive. TypeScript now caches some commonly used machinery to reuse across these operations.

我们做的另一个显著改进,提高了解析器的性能,是利用 var 偶尔绕过在闭包中使用 letconst 的开销。这改善了我们的一些解析性能。

🌐 Another notable change we made that improved our parser was leveraging var to occasionally side-step the cost of using let and const across closures. This improved some of our parsing performance.

总体而言,我们预计大多数代码库在使用 TypeScript 5.0 后都会看到速度提升,并且我们一直能够稳定地复现 10% 到 20% 的性能提升。当然,这将取决于硬件和代码库的特性,但我们鼓励你今天就在你的代码库上进行尝试!

🌐 Overall, we expect most codebases should see speed improvements from TypeScript 5.0, and have consistently been able to reproduce wins between 10% to 20%. Of course this will depend on hardware and codebase characteristics, but we encourage you to try it out on your codebase today!

更多信息,请参阅我们的一些显著优化:

🌐 For more information, see some of our notable optimizations:

重大变更和弃用

🌐 Breaking Changes and Deprecations

运行时要求

🌐 Runtime Requirements

TypeScript 现在以 ECMAScript 2018 为目标。 对于 Node 用户来说,这意味着最低需要 Node.js 10 或更高版本。

🌐 TypeScript now targets ECMAScript 2018. For Node users, that means a minimum version requirement of at least Node.js 10 and later.

lib.d.ts 变更

🌐 lib.d.ts Changes

DOM 类型生成方式的更改可能会影响现有代码。值得注意的是,某些属性已从 number 转换为数字字面量类型,并且剪切、复制和粘贴事件处理的属性和方法已在接口之间移动。

🌐 Changes to how types for the DOM are generated might have an impact on existing code. Notably, certain properties have been converted from number to numeric literal types, and properties and methods for cut, copy, and paste event handling have been moved across interfaces.

API 重大变更

🌐 API Breaking Changes

在 TypeScript 5.0 中,我们改用了模块,移除了一些不必要的接口,并进行了一些正确性改进。更多关于变更的详细信息,请参阅我们的 API 重大更改 页面。

🌐 In TypeScript 5.0, we moved to modules, removed some unnecessary interfaces, and made some correctness improvements. For more details on what’s changed, see our API Breaking Changes page.

关系运算符中禁止隐式强制转换

🌐 Forbidden Implicit Coercions in Relational Operators

如果你编写的代码可能导致隐式字符串到数字的强制转换,TypeScript 中的某些操作会触发警告:

🌐 Certain operations in TypeScript will already warn you if you write code which may cause an implicit string-to-number coercion:

ts
function func(ns: number | string) {
return ns * 4; // Error, possible implicit coercion
}

在 5.0 中,这也将应用于关系运算符 ><<=>=

🌐 In 5.0, this will also be applied to the relational operators >, <, <=, and >=:

ts
function func(ns: number | string) {
return ns > 4; // Now also an error
}

如果需要允许这样做,你可以使用 + 将操作数显式强制转换为 number

🌐 To allow this if desired, you can explicitly coerce the operand to a number using +:

ts
function func(ns: number | string) {
return +ns > 4; // OK
}

这一正确性改进Mateusz Burzyński提供。

🌐 This correctness improvement was contributed courtesy of Mateusz Burzyński.

枚举全面改进

🌐 Enum Overhaul

自 TypeScript 首次发布以来,enum 就存在一些长期存在的怪异现象。在 5.0 版本中,我们正在清理其中一些问题,同时减少理解你可以声明的各种 enum 所需的概念数量。

🌐 TypeScript has had some long-standing oddities around enums ever since its first release. In 5.0, we’re cleaning up some of these problems, as well as reducing the concept count needed to understand the various kinds of enums you can declare.

作为此的一部分,你可能会看到两种主要的新错误。第一个是,将一个域外的字面量赋值给 enum 类型现在会出现错误,这也在意料之中:

🌐 There are two main new errors you might see as part of this. The first is that assigning an out-of-domain literal to an enum type will now error as one might expect:

ts
enum SomeEvenDigit {
Zero = 0,
Two = 2,
Four = 4
}
// Now correctly an error
let m: SomeEvenDigit = 1;

另一种情况是,声明某些类型的间接混合字符串/数字 enum 形式会错误地生成全数字 enum:

🌐 The other is that declaration of certain kinds of indirected mixed string/number enum forms would, incorrectly, create an all-number enum:

ts
enum Letters {
A = "a"
}
enum Numbers {
one = 1,
two = Letters.A
}
// Now correctly an error
const t: number = Numbers.two;

你可以在相关更改中查看更多详细信息

🌐 You can see more details in relevant change.

--experimentalDecorators 下构造函数中参数装饰器的更精确类型检查

🌐 More Accurate Type-Checking for Parameter Decorators in Constructors Under --experimentalDecorators

TypeScript 5.0 使在 --experimentalDecorators 下对装饰器的类型检查更加准确。一个明显的例子是在构造函数参数上使用装饰器时。

🌐 TypeScript 5.0 makes type-checking more accurate for decorators under --experimentalDecorators. One place where this becomes apparent is when using a decorator on a constructor parameter.

ts
export declare const inject:
(entity: any) =>
(target: object, key: string | symbol, index?: number) => void;
export class Foo {}
export class C {
constructor(@inject(Foo) private x: any) {
}
}

此调用将失败,因为 key 期望一个 string | symbol,但构造函数参数接收到的是 undefined 的键。正确的修复方法是更改 injectkey 的类型。如果你使用的库无法升级,一个合理的解决方法是将 inject 封装在更类型安全的装饰器函数中,并对 key 使用类型断言。

🌐 This call will fail because key expects a string | symbol, but constructor parameters receive a key of undefined. The correct fix is to change the type of key within inject. A reasonable workaround if you’re using a library that can’t be upgraded is is to wrap inject in a more type-safe decorator function, and use a type-assertion on key.

有关更多详细信息,请参见此问题

🌐 For more details, see this issue.

弃用和默认变更

🌐 Deprecations and Default Changes

在 TypeScript 5.0 中,我们弃用了以下设置和设置值:

🌐 In TypeScript 5.0, we’ve deprecated the following settings and setting values:

  • --target: ES3
  • --out
  • --noImplicitUseStrict
  • --keyofStringsOnly
  • --suppressExcessPropertyErrors
  • --suppressImplicitAnyIndexErrors
  • --noStrictGenericChecks
  • --charset
  • --importsNotUsedAsValues
  • --preserveValueImports
  • 项目引用中的 prepend

这些配置将会继续被允许直到 TypeScript 5.5 届时将被完全移除,不过,如果你正在使用这些设置,将会收到警告。在 TypeScript 5.0 以及未来的 5.1、5.2、5.3 和 5.4 版本中,你可以指定 "ignoreDeprecations": "5.0" 来消除这些警告。我们也会很快发布一个 4.9 补丁,允许指定 ignoreDeprecations 以便进行更顺利的升级。除了弃用之外,我们还更改了一些设置,以更好地改善 TypeScript 的跨平台行为。

🌐 These configurations will continue to be allowed until TypeScript 5.5, at which point they will be removed entirely, however, you will receive a warning if you are using these settings. In TypeScript 5.0, as well as future releases 5.1, 5.2, 5.3, and 5.4, you can specify "ignoreDeprecations": "5.0" to silence those warnings. We’ll also shortly be releasing a 4.9 patch to allow specifying ignoreDeprecations to allow for smoother upgrades. Aside from deprecations, we’ve changed some settings to better improve cross-platform behavior in TypeScript.

--newLine,它控制 JavaScript 文件中输出的行结束符,如果未指定,过去会根据当前操作系统进行推断。我们认为构建过程应尽可能具有确定性,并且 Windows 记事本现在支持换行符结尾,因此新的默认设置是 LF。旧的基于操作系统的推断行为不再可用。

--forceConsistentCasingInFileNames,它确保项目中对同一文件名的所有引用在大小写上保持一致,现在默认使用 true。 这有助于发现那些在大小写不敏感的文件系统上编写的代码中的差异问题。

你可以留下反馈并查看有关 5.0 弃用问题跟踪 的更多信息

🌐 You can leave feedback and view more information on the tracking issue for 5.0 deprecations