⚠️ ARNING⚠️:本文中的所有内容均使用 Node.js 实验性功能。请确保你使用的 Node.js 版本支持本文中提到的功能。请记住,实验性功能可能会在 Node.js 的未来版本中发生变化。

¥⚠️WARNING⚠️: All content in this article uses Node.js experimental features. Please make sure you are using a version of Node.js that supports the features mentioned in this article. And remember that experimental features can change in future versions of Node.js.

原生运行 TypeScript

¥Running TypeScript Natively

在上一篇文章中,我们学习了如何使用转译和运行器运行 TypeScript 代码。在本文中,我们将学习如何使用 Node.js 本身运行 TypeScript 代码。

¥In the previous articles, we learned how to run TypeScript code using transpilation and with a runner. In this article, we will learn how to run TypeScript code using Node.js itself.

使用 Node.js 运行 TypeScript 代码

¥Running TypeScript code with Node.js

自 V22.6.0 以来,Node.js 通过 "类型剥离" 为某些 TypeScript 语法提供了实验性支持。你可以直接在 Node.js 中编写有效的 TypeScript 代码,而无需先对其进行转译。

¥Since V22.6.0, Node.js has experimental support for some TypeScript syntax via "type stripping". You can write code that's valid TypeScript directly in Node.js without the need to transpile it first.

--experimental-strip-types 标志告诉 Node.js 在运行 TypeScript 代码之前从中剥离类型注释。

¥The --experimental-strip-types flag tells Node.js to strip the type annotations from the TypeScript code before running it.

node --experimental-strip-types example.ts

就是这样!你现在可以在 Node.js 中直接运行 TypeScript 代码,而无需先对其进行转译,并使用 TypeScript 捕获与类型相关的错误。

¥And that's it! You can now run TypeScript code directly in Node.js without the need to transpile it first, and use TypeScript to catch type-related errors.

在 V22.7.0 中,此实验性支持已扩展为转换仅限 TypeScript 的语法,如 enumnamespace,并添加了 --experimental-transform-types 标志。

¥In V22.7.0 this experimental support was extended to transform TypeScript-only syntax, like enums and namespace, with the addition of the --experimental-transform-types flag.

node --experimental-strip-types --experimental-transform-types another-example.ts

Node.js 的未来版本将包含对 TypeScript 的支持,而无需命令行标志。

¥Future versions of Node.js will include support for TypeScript without the need for a command line flag.

限制

¥Limitations

在撰写本文时,Node.js 中对 TypeScript 的实验性支持存在一些限制。

¥At the time of writing, the experimental support for TypeScript in Node.js has some limitations.

你可以获取有关 API 文档 的更多信息。

¥You can get more information on the API docs.

重要说明

¥Important notes

感谢所有使此功能成为可能的贡献者。我们希望此功能很快会在 Node.js 的 LTS 版本中稳定可用。

¥Thanks to all the contributors who have made this feature possible. We hope that this feature will be stable and available in the LTS version of Node.js soon.

我们可以理解此功能是实验性的并且有一些限制;如果这不适合你的用例,请使用其他代码或提供修复。也欢迎错误报告,请记住该项目是由志愿者运行的,不提供任何形式的保证,因此如果你无法自己贡献修复,请耐心等待。

¥We can understand that this feature is experimental and has some limitations; if that doesn't suit your use-case, please use something else, or contribute a fix. Bug reports are also welcome, please keep in mind the project is run by volunteers, without warranty of any kind, so please be patient if you can't contribute the fix yourself.