通过转译运行 TypeScript 代码
🌐 Running TypeScript code using transpilation
转译是将源代码从一种语言转换为另一种语言的过程。对于 TypeScript 来说,这个过程就是将 TypeScript 代码转换为 JavaScript 代码。这是必要的,因为浏览器和 Node.js 不能直接运行 TypeScript 代码。
🌐 Transpilation is the process of converting source code from one language to another. In the case of TypeScript, it's the process of converting TypeScript code to JavaScript code. This is necessary because browsers and Node.js don't run TypeScript code directly.
将 TypeScript 编译为 JavaScript
🌐 Compiling TypeScript to JavaScript
运行 TypeScript 代码最常见的方法是先将其编译成 JavaScript。你可以使用 TypeScript 编译器 tsc 来完成这个操作。
🌐 The most common way to run TypeScript code is to compile it to JavaScript first. You can do this using the TypeScript compiler tsc.
步骤 1: 在文件中编写你的 TypeScript 代码,例如 example.ts。
type = {
: string;
: number;
};
function (: ): boolean {
return . >= 18;
}
const = {
: 'Justine',
: 23,
} satisfies ;
const = ();
步骤 2: 使用包管理器在本地安装 TypeScript:
在这个例子中,我们将使用 npm,你可以查看 我们关于 npm 包管理器的介绍 以获取更多信息。
🌐 In this example we're going to use npm, you can check our introduction to the npm package manager for more information.
npm i -D typescript # -D is a shorthand for --save-dev
步骤 3: 使用 tsc 命令将你的 TypeScript 代码编译为 JavaScript:
npx tsc example.ts
注意:
npx是一个工具,允许你在不全局安装的情况下运行 Node.js 包。
tsc 是 TypeScript 编译器,它会将我们的 TypeScript 代码编译成 JavaScript。
这个命令会生成一个名为 example.js 的新文件,我们可以使用 Node.js 运行它。
现在,当我们知道如何编译和运行 TypeScript 代码后,让我们看看 TypeScript 防止错误的功能如何发挥作用!
步骤 4: 使用 Node.js 运行你的 JavaScript 代码:
node example.js
你应该在终端中看到 TypeScript 代码的输出
🌐 You should see the output of your TypeScript code in the terminal
如果存在类型错误
🌐 If there are type errors
如果你的 TypeScript 代码中有类型错误,TypeScript 编译器会捕捉到它们,并阻止你运行代码。例如,如果你将 justine 的 age 属性改为字符串,TypeScript 会报错:
🌐 If you have type errors in your TypeScript code, the TypeScript compiler will catch them and prevent you from running the code. For example, if you change the age property of justine to a string, TypeScript will throw an error:
我们将像这样修改我们的代码,以自愿引入类型错误:
🌐 We will modify our code like this, to voluntarily introduce a type error:
type = {
: string;
: number;
};
function (: ): boolean {
return . >= 18;
}
const : = {
: 'Justine',
age: 'Secret!',};
const isJustineAnAdult: string = (, "I shouldn't be here!");正如你所看到的,TypeScript 在错误发生之前就能帮助发现它们。这也是 TypeScript 在开发者中如此受欢迎的原因之一。
🌐 As you can see, TypeScript is very helpful in catching bugs before they even happen. This is one of the reasons why TypeScript is so popular among developers.