satisfies 运算符
🌐 The satisfies Operator
TypeScript 开发者经常会遇到一个两难问题:我们希望确保某个表达式匹配某种类型,但同时又希望保留该表达式的最具体类型以用于类型推断。
🌐 TypeScript developers are often faced with a dilemma: we want to ensure that some expression matches some type, but also want to keep the most specific type of that expression for inference purposes.
例如:
🌐 For example:
ts// Each property can be a string or an RGB tuple.const palette = {red: [255, 0, 0],green: "#00ff00",bleu: [0, 0, 255]// ^^^^ sacrebleu - we've made a typo!};// We want to be able to use string methods on 'green'...const greenNormalized = palette.green.toUpperCase();
请注意,我们写了 bleu,但我们可能应该写成 blue。
我们可以尝试通过在 palette 上使用类型注解来捕捉 bleu 的拼写错误,但这样会丢失关于每个属性的信息。
🌐 Notice that we’ve written bleu, whereas we probably should have written blue.
We could try to catch that bleu typo by using a type annotation on palette, but we’d lose the information about each property.
tstype Colors = "red" | "green" | "blue";type RGB = [red: number, green: number, blue: number];const palette: Record<Colors, string | RGB> = {red: [255, 0, 0],green: "#00ff00",bleu: [0, 0, 255]// ~~~~ The typo is now correctly detected};// But we now have an undesirable error here - 'palette.green' "could" be of type RGB and// property 'toUpperCase' does not exist on type 'string | RGB'.const greenNormalized = palette.green.toUpperCase();
新的 satisfies 运算符允许我们验证一个表达式的类型是否与某种类型匹配,而不会改变该表达式的结果类型。举例来说,我们可以使用 satisfies 来验证 palette 的所有属性是否与 string | number[] 兼容:
🌐 The new satisfies operator lets us validate that the type of an expression matches some type, without changing the resulting type of that expression.
As an example, we could use satisfies to validate that all the properties of palette are compatible with string | number[]:
tstype Colors = "red" | "green" | "blue";type RGB = [red: number, green: number, blue: number];const palette = {red: [255, 0, 0],green: "#00ff00",bleu: [0, 0, 255]// ~~~~ The typo is now caught!} satisfies Record<Colors, string | RGB>;// toUpperCase() method is still accessible!const greenNormalized = palette.green.toUpperCase();
satisfies 可用于捕获许多可能的错误。例如,我们可以确保一个对象拥有某种类型的所有键,但不会有额外键:
tstype Colors = "red" | "green" | "blue";// Ensure that we have exactly the keys from 'Colors'.const favoriteColors = {"red": "yes","green": false,"blue": "kinda","platypus": false// ~~~~~~~~~~ error - "platypus" was never listed in 'Colors'.} satisfies Record<Colors, unknown>;// All the information about the 'red', 'green', and 'blue' properties are retained.const g: boolean = favoriteColors.green;
也许我们不在意属性名称是否匹配,但我们确实关心每个属性的类型。在这种情况下,我们也可以确保对象的所有属性值都符合某种类型。
🌐 Maybe we don’t care about if the property names match up somehow, but we do care about the types of each property. In that case, we can also ensure that all of an object’s property values conform to some type.
tstype RGB = [red: number, green: number, blue: number];const palette = {red: [255, 0, 0],green: "#00ff00",blue: [0, 0]// ~~~~~~ error!} satisfies Record<string, string | RGB>;// Information about each property is still maintained.const redComponent = palette.red.at(0);const greenNormalized = palette.green.toUpperCase();
更多示例,请参见提出此问题的链接和实现的拉取请求。 我们要感谢Oleksandr Tarasiuk与我们一起实现并迭代了此功能。
🌐 For more examples, you can see the issue proposing this and the implementing pull request. We’d like to thank Oleksandr Tarasiuk who implemented and iterated on this feature with us.
使用 in 操作符未列出的属性缩小
🌐 Unlisted Property Narrowing with the in Operator
作为开发者,我们经常需要处理在运行时并不完全已知的值。实际上,我们常常不知道某个属性是否存在,无论是从服务器获取响应还是读取配置文件。JavaScript 的 in 运算符可以检查对象上是否存在某个属性。
🌐 As developers, we often need to deal with values that aren’t fully known at runtime.
In fact, we often don’t know if properties exist, whether we’re getting a response from a server or reading a configuration file.
JavaScript’s in operator can check whether a property
exists on an object.
以前,TypeScript 允许我们缩小未明确列出属性的类型范围。
🌐 Previously, TypeScript allowed us to narrow away any types that don’t explicitly list a property.
tsinterface RGB {red: number;green: number;blue: number;}interface HSV {hue: number;saturation: number;value: number;}function setColor(color: RGB | HSV) {if ("hue" in color) {// 'color' now has the type HSV}// ...}
在这里,类型 RGB 没有列出 hue,因此被缩小了,剩下的就是类型 HSV。
🌐 Here, the type RGB didn’t list the hue and got narrowed away, and leaving us with the type HSV.
但是那些没有类型列出某个属性的例子呢?在这些情况下,语言对我们帮助不大。让我们看以下 JavaScript 示例:
🌐 But what about examples where no type listed a given property? In those cases, the language didn’t help us much. Let’s take the following example in JavaScript:
jsfunction tryGetPackageName(context) {const packageJSON = context.packageJSON;// Check to see if we have an object.if (packageJSON && typeof packageJSON === "object") {// Check to see if it has a string name property.if ("name" in packageJSON && typeof packageJSON.name === "string") {return packageJSON.name;}}return undefined;}
将此重写为标准 TypeScript 只是一个为 context 定义并使用类型的问题;然而,为 packageJSON 属性选择像 unknown 这样安全的类型会在旧版本 TypeScript 中引发问题。
🌐 Rewriting this to canonical TypeScript would just be a matter of defining and using a type for context;
however, picking a safe type like unknown for the packageJSON property would cause issues in older versions of TypeScript.
tsinterface Context {packageJSON: unknown;}function tryGetPackageName(context: Context) {const packageJSON = context.packageJSON;// Check to see if we have an object.if (packageJSON && typeof packageJSON === "object") {// Check to see if it has a string name property.if ("name" in packageJSON && typeof packageJSON.name === "string") {// ~~~~// error! Property 'name' does not exist on type 'object.return packageJSON.name;// ~~~~// error! Property 'name' does not exist on type 'object.}}return undefined;}
这是因为虽然 packageJSON 的类型从 unknown 缩小到了 object,但 in 操作符严格缩小到了实际定义了正在检查的属性的类型。结果,packageJSON 的类型仍然是 object。
🌐 This is because while the type of packageJSON was narrowed from unknown to object, the in operator strictly narrowed to types that actually defined the property being checked.
As a result, the type of packageJSON remained object.
TypeScript 4.9 在缩小完全没有列出该属性的类型时,使 in 操作符更加强大。语言不会再保持它们原样,而是将它们的类型与 Record<"property-key-being-checked", unknown> 相交。
🌐 TypeScript 4.9 makes the in operator a little bit more powerful when narrowing types that don’t list the property at all.
Instead of leaving them as-is, the language will intersect their types with Record<"property-key-being-checked", unknown>.
所以在我们的示例中,packageJSON 的类型会从 unknown 缩小到 object 再到 object & Record<"name", unknown>。这使我们可以直接访问 packageJSON.name 并独立地缩小其类型。
🌐 So in our example, packageJSON will have its type narrowed from unknown to object to object & Record<"name", unknown>
That allows us to access packageJSON.name directly and narrow that independently.
tsinterface Context {packageJSON: unknown;}function tryGetPackageName(context: Context): string | undefined {const packageJSON = context.packageJSON;// Check to see if we have an object.if (packageJSON && typeof packageJSON === "object") {// Check to see if it has a string name property.if ("name" in packageJSON && typeof packageJSON.name === "string") {// Just works!return packageJSON.name;}}return undefined;}
TypeScript 4.9 还加强了对 in 使用方式的一些检查,确保左侧的值可以分配给类型 string | number | symbol,右侧的值可以分配给 object。
这有助于检查我们是否使用了有效的属性键,而不是意外地检查了基本类型。
🌐 TypeScript 4.9 also tightens up a few checks around how in is used, ensuring that the left side is assignable to the type string | number | symbol, and the right side is assignable to object.
This helps check that we’re using valid property keys, and not accidentally checking primitives.
欲了解更多信息,请阅读实现拉取请求
🌐 For more information, read the implementing pull request
类中的自动访问器
🌐 Auto-Accessors in Classes
TypeScript 4.9 支持 ECMAScript 中即将推出的一个特性,称为自动访问器。自动访问器的声明方式与类中的属性相同,只是它们使用 accessor 关键字声明。
🌐 TypeScript 4.9 supports an upcoming feature in ECMAScript called auto-accessors.
Auto-accessors are declared just like properties on classes, except that they’re declared with the accessor keyword.
tsclass Person {accessor name: string;constructor(name: string) {this.name = name;}}
在表面之下,这些自动访问器被“去糖化”成具有不可达私有属性的 get 和 set 访问器。
🌐 Under the covers, these auto-accessors “de-sugar” to a get and set accessor with an unreachable private property.
tsclass Person {#__name: string;get name() {return this.#__name;}set name(value: string) {this.#__name = value;}constructor(name: string) {this.name = name;}}
你可以在原始 PR 上查看更多关于自动访问器的拉取请求。
🌐 You can read up more about the auto-accessors pull request on the original PR.
检查 NaN 相等性
🌐 Checks For Equality on NaN
对于 JavaScript 开发者来说,一个主要的陷阱是使用内置的相等运算符来检查值 NaN。
🌐 A major gotcha for JavaScript developers is checking against the value NaN using the built-in equality operators.
为了提供一些背景,NaN 是一个特殊的数值,表示“不是数字”。没有任何东西等于 NaN - 甚至 NaN 也不行!
🌐 For some background, NaN is a special numeric value that stands for “Not a Number”.
Nothing is ever equal to NaN - even NaN!
jsconsole.log(NaN == 0) // falseconsole.log(NaN === 0) // falseconsole.log(NaN == NaN) // falseconsole.log(NaN === NaN) // false
但至少从对称角度来看,所有东西总是不等于 NaN。
🌐 But at least symmetrically everything is always not-equal to NaN.
jsconsole.log(NaN != 0) // trueconsole.log(NaN !== 0) // trueconsole.log(NaN != NaN) // trueconsole.log(NaN !== NaN) // true
从技术上讲,这并不是 JavaScript 特有的问题,因为任何包含 IEEE-754 浮点数的语言都有相同的行为;但 JavaScript 的主要数值类型是浮点数,而 JavaScript 中的数字解析往往会导致 NaN。 反过来,检测 NaN 变得相当常见,正确的做法是使用 Number.isNaN - 但是,正如我们提到的,很多人最终会错误地使用 someValue === NaN 来进行检查。
🌐 This technically isn’t a JavaScript-specific problem, since any language that contains IEEE-754 floats has the same behavior;
but JavaScript’s primary numeric type is a floating point number, and number parsing in JavaScript can often result in NaN.
In turn, checking against NaN ends up being fairly common, and the correct way to do so is to use Number.isNaN - but as we mentioned, lots of people accidentally end up checking with someValue === NaN instead.
TypeScript 现在在直接与 NaN 比较时会报错,并且会建议改用某种形式的 Number.isNaN。
🌐 TypeScript now errors on direct comparisons against NaN, and will suggest using some variation of Number.isNaN instead.
tsfunction validate(someValue: number) {return someValue !== NaN;// ~~~~~~~~~~~~~~~~~// error: This condition will always return 'true'.// Did you mean '!Number.isNaN(someValue)'?}
我们认为这项更改应该严格地有助于捕获初学者的错误,类似于 TypeScript 目前在与对象和数组字面量进行比较时触发的错误。
🌐 We believe that this change should strictly help catch beginner errors, similar to how TypeScript currently issues errors on comparisons against object and array literals.
我们要感谢 Oleksandr Tarasiuk,他贡献了这个检查。
🌐 We’d like to extend our thanks to Oleksandr Tarasiuk who contributed this check.
文件监视现在使用文件系统事件
🌐 File-Watching Now Uses File System Events
在早期版本中,TypeScript 在监视单个文件时严重依赖轮询。
使用轮询策略意味着定期检查文件的状态以获取更新。
在 Node.js 上,fs.watchFile 是获取轮询文件监视器的内置方法。
虽然轮询在跨平台和文件系统中通常更可预测,但这意味着即使文件没有更改,你的 CPU 也必须定期中断并检查文件更新。
对于几十个文件来说,这可能不明显;
但对于包含大量文件的较大项目——或 node_modules 中的许多文件——这可能会消耗大量资源。
🌐 In earlier versions, TypeScript leaned heavily on polling for watching individual files.
Using a polling strategy meant checking the state of a file periodically for updates.
On Node.js, fs.watchFile is the built-in way to get a polling file-watcher.
While polling tends to be more predictable across platforms and file systems, it means that your CPU has to periodically get interrupted and check for updates to the file, even when nothing’s changed.
For a few dozen files, this might not be noticeable;
but on a bigger project with lots of files - or lots of files in node_modules - this can become a resource hog.
一般来说,更好的方法是使用文件系统事件。
我们可以不通过轮询,而是声明我们对特定文件的更新感兴趣,并提供一个回调函数,当这些文件实际发生变化时会触发。
大多数现代平台都提供了类似 CreateIoCompletionPort、kqueue、epoll 和 inotify 的设施和 API。
Node.js 大多通过提供 fs.watch 对这些进行了抽象。
文件系统事件通常效果很好,但使用它们仍有许多注意事项,进而在使用 fs.watch API 时也同样需要注意。
监视器需要谨慎考虑 inode 监控、在某些文件系统上的[不可用性](https://nodejs.cn/docs/latest-v18.x/api/fs.html#availability)(例如网络文件系统)、是否支持递归文件监控、目录重命名是否触发事件,甚至文件监视器可能会耗尽!
换句话说,这并不是免费的午餐,特别是如果你正在寻找跨平台解决方案。
🌐 Generally speaking, a better approach is to use file system events.
Instead of polling, we can announce that we’re interested in updates of specific files and provide a callback for when those files actually do change.
Most modern platforms in use provide facilities and APIs like CreateIoCompletionPort, kqueue, epoll, and inotify.
Node.js mostly abstracts these away by providing fs.watch.
File system events usually work great, but there are lots of caveats to using them, and in turn, to using the fs.watch API.
A watcher needs to be careful to consider inode watching, unavailability on certain file systems (e.g.networked file systems), whether recursive file watching is available, whether directory renames trigger events, and even file watcher exhaustion!
In other words, it’s not quite a free lunch, especially if you’re looking for something cross-platform.
因此,我们默认选择的是最低的共同标准:民意调查。并非总是如此,但大多数时候都是这样。
🌐 As a result, our default was to pick the lowest common denominator: polling. Not always, but most of the time.
随着时间的推移,我们提供了选择其他文件监控策略的方法。这使我们能够获得反馈,并使我们的文件监控实现更加稳健,应对大多数平台特定的问题。随着 TypeScript 需要扩展到更大的代码库,并且在这方面有所改进,我们认为将文件系统事件作为默认方式是一项值得的投资。
🌐 Over time, we’ve provided the means to choose other file-watching strategies. This allowed us to get feedback and harden our file-watching implementation against most of these platform-specific gotchas. As TypeScript has needed to scale to larger codebases, and has improved in this area, we felt swapping to file system events as the default would be a worthwhile investment.
在 TypeScript 4.9 中,文件监视默认由文件系统事件驱动,只有在无法设置基于事件的监视器时才会回退到轮询。对于大多数开发者来说,当以 --watch 模式运行,或使用像 Visual Studio 或 VS Code 这样的 TypeScript 驱动的编辑器时,这应该提供一个资源消耗更低的体验。
🌐 In TypeScript 4.9, file watching is powered by file system events by default, only falling back to polling if we fail to set up event-based watchers.
For most developers, this should provide a much less resource-intensive experience when running in --watch mode, or running with a TypeScript-powered editor like Visual Studio or VS Code.
文件监视的工作方式仍然可以通过环境变量和 watchOptions 进行配置——并且 一些编辑器如 VS Code 可以独立支持 watchOptions。
使用更特殊配置的开发者,比如源代码存放在网络文件系统(如 NFS 和 SMB)上的情况,可能需要选择恢复使用旧的行为;不过,如果服务器的处理能力足够强,启用 SSH 并远程运行 TypeScript 以直接访问本地文件可能会更好。
VS Code 有大量的 远程扩展 来简化这一过程。
你可以在 GitHub 上阅读有关此更改的更多信息。
🌐 You can read up more on this change on GitHub.
编辑器的“删除未使用的导入”和“整理导入”命令
🌐 “Remove Unused Imports” and “Sort Imports” Commands for Editors
以前,TypeScript 仅支持两个用于管理导入的编辑器命令。对于我们的示例,请看以下代码:
🌐 Previously, TypeScript only supported two editor commands to manage imports. For our examples, take the following code:
tsimport { Zebra, Moose, HoneyBadger } from "./zoo";import { foo, bar } from "./helper";let x: Moose | HoneyBadger = foo();
第一个叫做“整理导入”,它会移除未使用的导入,然后对剩下的导入进行排序。它会将该文件重写成如下所示:
🌐 The first was called “Organize Imports” which would remove unused imports, and then sort the remaining ones. It would rewrite that file to look like this one:
tsimport { foo } from "./helper";import { HoneyBadger, Moose } from "./zoo";let x: Moose | HoneyBadger = foo();
在 TypeScript 4.3 中,我们引入了一个名为“Sort Imports”的命令,它只会对文件中的导入进行排序,而不会移除它们——并会像这样重写文件。
🌐 In TypeScript 4.3, we introduced a command called “Sort Imports” which would only sort imports in the file, but not remove them - and would rewrite the file like this.
tsimport { bar, foo } from "./helper";import { HoneyBadger, Moose, Zebra } from "./zoo";let x: Moose | HoneyBadger = foo();
“排序导入”的注意事项是,在 Visual Studio Code 中,这个功能仅作为保存时的命令可用,而不能手动触发执行。
🌐 The caveat with “Sort Imports” was that in Visual Studio Code, this feature was only available as an on-save command - not as a manually triggerable command.
TypeScript 4.9 增加了另一半功能,现在提供“移除未使用的导入”。 TypeScript 现在会移除未使用的导入名称和语句,但会保留相对顺序不变。
🌐 TypeScript 4.9 adds the other half, and now provides “Remove Unused Imports”. TypeScript will now remove unused import names and statements, but will otherwise leave the relative ordering alone.
tsimport { Moose, HoneyBadger } from "./zoo";import { foo } from "./helper";let x: Moose | HoneyBadger = foo();
此功能适用于所有希望使用任一命令的编辑器;但值得注意的是,Visual Studio Code(1.73 及更高版本)将内置支持此功能,并通过其命令面板呈现这些命令。喜欢使用更细分的“移除未使用的导入”或“排序导入”命令的用户,可以根据需要将“组织导入”的快捷键重新分配给它们。
🌐 This feature is available to all editors that wish to use either command; but notably, Visual Studio Code (1.73 and later) will have support built in and will surface these commands via its Command Palette. Users who prefer to use the more granular “Remove Unused Imports” or “Sort Imports” commands should be able to reassign the “Organize Imports” key combination to them if desired.
你可以在这里查看功能的具体信息。
🌐 You can view specifics of the feature here.
在 return 关键字上转到定义
🌐 Go-to-Definition on return Keywords
在编辑器中,当对 return 关键字执行“转到定义”时,TypeScript 现在会将你跳转到相应函数的顶部。 这对于快速了解 return 属于哪个函数非常有帮助。
🌐 In the editor, when running a go-to-definition on the return keyword, TypeScript will now jump you to the top of the corresponding function.
This can be helpful to get a quick sense of which function a return belongs to.
我们预计 TypeScript 将会将此功能扩展到更多关键字 例如 await 和 yield 或 switch、case 和 default。
🌐 We expect TypeScript will expand this functionality to more keywords such as await and yield or switch, case, and default.
性能改进
🌐 Performance Improvements
TypeScript 有一些虽小但显著的性能改进。
🌐 TypeScript has a few small, but notable, performance improvements.
首先,TypeScript 的 forEachChild 函数已被重写为使用函数表查找,而不是在所有语法节点上使用 switch 语句。
forEachChild 是编译器中遍历语法节点的主力函数,在编译器的绑定阶段以及语言服务的某些部分被广泛使用。
对 forEachChild 的重构使我们的绑定阶段和语言服务操作所花费的时间最多减少了 20%。
🌐 First, TypeScript’s forEachChild function has been rewritten to use a function table lookup instead of a switch statement across all syntax nodes.
forEachChild is a workhorse for traversing syntax nodes in the compiler, and is used heavily in the binding stage of our compiler, along with parts of the language service.
The refactoring of forEachChild yielded up to a 20% reduction of time spent in our binding phase and across language service operations.
一旦我们发现了 forEachChild 的性能提升,我们就将其尝试应用到 visitEachChild 上,这是我们在编译器和语言服务中用来转换节点的一个函数。相同的重构在生成项目输出的时间上最多减少了 3% 。
🌐 Once we discovered this performance win for forEachChild, we tried it out on visitEachChild, a function we use for transforming nodes in the compiler and language service.
The same refactoring yielded up to a 3% reduction in time spent in generating project output.
在 forEachChild 的初步探索是受 Artemis Everfree 的一篇 博客文章 启发的。虽然我们有一些理由相信速度提升的根本原因可能更多与函数的大小/复杂性有关,而不是博客文章中描述的问题,但我们仍然很感激能够从这次经历中学习,并尝试一个相对快速的重构,从而使 TypeScript 运行得更快。
🌐 The initial exploration in forEachChild was inspired by a blog post by Artemis Everfree.
While we have some reason to believe the root cause of our speed-up might have more to do with function size/complexity than the issues described in the blog post, we’re grateful that we were able to learn from the experience and try out a relatively quick refactoring that made TypeScript faster.
最后,TypeScript 在条件类型的真分支中保留类型信息的方式已被优化。在像这样的类型中
🌐 Finally, the way TypeScript preserves the information about a type in the true branch of a conditional type has been optimized. In a type like
tsinterface Zoo<T extends Animal> {// ...}type MakeZoo<A> = A extends Animal ? Zoo<A> : never;
TypeScript 必须“记住” A 在检查 Zoo<A> 是否有效时也必须是 Animal。
这基本上是通过创建一个用于保存 A 与 Animal 交集的特殊类型来完成的;
然而,TypeScript 之前是急切地执行这一操作,但这并非总是必要的。
此外,我们类型检查器中的一些错误代码阻止了这些特殊类型的简化。
TypeScript 现在会推迟这些类型的交集操作,直到确实有必要的时候。
对于大量使用条件类型的代码库,你可能会看到 TypeScript 的显著加速,但在我们的性能测试套件中,我们只观察到类型检查时间减少了大约 3%。
🌐 TypeScript has to “remember” that A must also be an Animal when checking if Zoo<A> is valid.
This is basically done by creating a special type that used to hold the intersection of A with Animal;
however, TypeScript previously did this eagerly which isn’t always necessary.
Furthermore, some faulty code in our type-checker prevented these special types from being simplified.
TypeScript now defers intersecting these types until it’s necessary.
For codebases with heavy use of conditional types, you might witness significant speed-ups with TypeScript, but in our performance testing suite, we saw a more modest 3% reduction in type-checking time.
你可以在各自的拉取请求中了解更多关于这些优化的信息:
🌐 You can read up more on these optimizations on their respective pull requests:
错误修复和重大变更
🌐 Correctness Fixes and Breaking Changes
lib.d.ts 更新
🌐 lib.d.ts Updates
虽然 TypeScript 力求避免重大破坏,但内置库的即使是很小的更改也可能引发问题。我们预计 DOM 和 lib.d.ts 更新不会导致重大破坏,但可能会有一些小问题。
🌐 While TypeScript strives to avoid major breaks, even small changes in the built-in libraries can cause issues.
We don’t expect major breaks as a result of DOM and lib.d.ts updates, but there may be some small ones.
Promise.resolve 的更好类型
🌐 Better Types for Promise.resolve
Promise.resolve 现在使用 Awaited 类型来拆解传入的类似 Promise 的类型。这意味着它更频繁地返回正确的 Promise 类型,但这种改进的类型可能会破坏现有代码,如果代码之前期望的是 any 或 unknown 而不是 Promise。更多信息,请 查看原始更改。
JavaScript Emit 不再省略导入
🌐 JavaScript Emit No Longer Elides Imports
当 TypeScript 首次支持 JavaScript 的类型检查和编译时,它意外地支持了一个名为导入消除(import elision)的功能。简而言之,如果一个导入没有作为值被使用,或者编译器可以检测到该导入在运行时不会引用到值,编译器将在生成时删除该导入。
🌐 When TypeScript first supported type-checking and compilation for JavaScript, it accidentally supported a feature called import elision. In short, if an import is not used as a value, or the compiler can detect that the import doesn’t refer to a value at runtime, the compiler will drop the import during emit.
这种行为值得质疑,特别是检测导入是否不指向某个值,因为这意味着 TypeScript 有时必须依赖可能不准确的声明文件。反过来,TypeScript 现在会在 JavaScript 文件中保留导入。
🌐 This behavior was questionable, especially the detection of whether the import doesn’t refer to a value, since it means that TypeScript has to trust sometimes-inaccurate declaration files. In turn, TypeScript now preserves imports in JavaScript files.
js// Input:import { someValue, SomeClass } from "some-module";/** @type {SomeClass} */let val = someValue;// Previous Output:import { someValue } from "some-module";/** @type {SomeClass} */let val = someValue;// Current Output:import { someValue, SomeClass } from "some-module";/** @type {SomeClass} */let val = someValue;
更多信息可在实现变更中找到。
🌐 More information is available at the implementing change.
exports 优先于 typesVersions
🌐 exports is Prioritized Over typesVersions
以前,TypeScript 在通过 --moduleResolution node16 下的 package.json 解析时错误地优先考虑了 typesVersions 字段而不是 exports 字段。如果此更改影响到你的库,你可能需要在 package.json 的 exports 字段中添加 types@ 版本选择器。
🌐 Previously, TypeScript incorrectly prioritized the typesVersions field over the exports field when resolving through a package.json under --moduleResolution node16.
If this change impacts your library, you may need to add types@ version selectors in your package.json’s exports field.
diff{"type": "module","main": "./dist/main.js""typesVersions": {"<4.8": { ".": ["4.8-types/main.d.ts"] },"*": { ".": ["modern-types/main.d.ts"] }},"exports": {".": {+ "types@<4.8": "./4.8-types/main.d.ts",+ "types": "./modern-types/main.d.ts","import": "./dist/main.js"}}}
欲了解更多信息,请参阅此 拉取请求。
🌐 For more information, see this pull request.
SubstitutionType 的 substitute 已被替换为 constraint
🌐 substitute Replaced With constraint on SubstitutionTypes
作为对替代类型优化的一部分,SubstitutionType 对象不再包含表示有效替代的 substitute 属性(通常是基类型和隐式约束的交集)——相反,它们仅包含 constraint 属性。
🌐 As part of an optimization on substitution types, SubstitutionType objects no longer contain the substitute property representing the effective substitution (usually an intersection of the base type and the implicit constraint) - instead, they just contain the constraint property.
欲了解更多详情,请阅读原始拉取请求。
🌐 For more details, read more on the original pull request.