使用转译运行 TypeScript 代码

转译是将源代码从一种语言转换为另一种语言的过程。在 TypeScript 的情况下,它是将 TypeScript 代码转换为 JavaScript 代码的过程。这是必要的,因为浏览器和 Node.js 不会直接运行 TypeScript 代码。

将 TypeScript 编译为 JavaScript

运行 TypeScript 代码最常见的方法是首先将其编译为 JavaScript。您可以使用 TypeScript 编译器 tsc 来完成此操作。

步骤 1: 在文件中编写您的 TypeScript 代码,例如 example.ts

type User = {
  name: string;
  age: number;
};

function isAdult(user: User): boolean {
  return user.age >= 18;
}

const justine = {
  name: 'Justine',
  age: 23,
} satisfies User;

const isJustineAnAdult = isAdult(justine);

步骤 2: 使用包管理器在本地安装 TypeScript

在此示例中,我们将使用 npm,您可以查看我们对 npm 包管理器的介绍以获取更多信息。

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 代码的输出

如果存在类型错误

如果您的 TypeScript 代码中存在类型错误,TypeScript 编译器会捕获它们并阻止您运行该代码。例如,如果您将 justineage 属性更改为字符串,TypeScript 将抛出一个错误

我们将像这样修改我们的代码,以自愿引入一个类型错误

type User = {
  name: string;
  age: number;
};

function isAdult(user: User): boolean {
  return user.age >= 18;
}

const justine: User = {
  name: 'Justine',
  age: 'Secret!',
};

const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!");

这就是 TypeScript 对此的看法

example.ts:12:5 - error TS2322: Type 'string' is not assignable to type 'number'.

12     age: 'Secret!',
       ~~~

  example.ts:3:5
    3     age: number;
          ~~~
    The expected type comes from property 'age' which is declared here on type 'User'

example.ts:15:7 - error TS2322: Type 'boolean' is not assignable to type 'string'.

15 const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!");
         ~~~~~~~~~~~~~~~~

example.ts:15:51 - error TS2554: Expected 1 arguments, but got 2.

15 const isJustineAnAdult: string = isAdult(justine, "I shouldn't be here!");
                                                     ~~~~~~~~~~~~~~~~~~~~~~


Found 3 errors in the same file, starting at: example.ts:12

正如您所看到的,TypeScript 在捕获错误方面非常有用,甚至在错误发生之前就发现了。这就是 TypeScript 在开发人员中如此受欢迎的原因之一。