⚠️ 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. You can write code that's valid TypeScript directly in Node.js without the need to transpile it first.

那么如何使用 Node.js 运行 TypeScript 代码?

¥So how do you run TypeScript code with Node.js?

node --experimental-strip-types example.ts

--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.js 中直接运行 TypeScript 代码,而无需先对其进行转译,并使用 TypeScript 捕获与类型相关的错误。Node.js 的未来版本将包含对 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. Future versions of Node.js will include support for TypeScript without the need for a command line flag.

限制

¥Limitations

在撰写本文时,Node.js 中对 TypeScript 的实验性支持存在一些限制。为了让 TypeScript 能够在 node.js 中运行,我们的合作者选择仅从代码中剥离类型。

¥At the time of writing, the experimental support for TypeScript in Node.js has some limitations. To allow TypeScript to run in node.js, our collaborators have chosen to only strip types from the code.

你可以获取有关 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.