使用 TypeScript 的 Node.js

¥Node.js with TypeScript

什么是 TypeScript

¥What is TypeScript

TypeScript 是一种由 Microsoft 维护和开发的开源语言。它受到世界各地许多软件开发者的喜爱和使用。

¥TypeScript is an open-source language maintained and developed by Microsoft. It's loved and used by a lot of software developers around the world.

基本上,它是 JavaScript 的超集,为语言添加了新功能。最值得注意的新增功能是静态类型定义,这是纯 JavaScript 中不存在的。由于类型,例如,可以声明我们期望什么样的参数以及我们的函数中究竟返回什么,或者我们正在创建的对象的确切形状是什么。TypeScript 是一个非常强大的工具,为 JavaScript 项目开辟了一个新的可能性世界。它通过在代码交付之前防止许多错误,使我们的代码更加安全和强大 - 它会在代码开发过程中捕获问题,并与 Visual Studio Code 等代码编辑器完美集成。

¥Basically, it's a superset of JavaScript that adds new capabilities to the language. The most notable addition is static type definitions, something that is not present in plain JavaScript. Thanks to types, it's possible, for example, to declare what kind of arguments we are expecting and what is returned exactly in our functions or what's the exact shape of the object that we are creating. TypeScript is a really powerful tool and opens a new world of possibilities in JavaScript projects. It makes our code more secure and robust by preventing many bugs before the code is even shipped - it catches problems during code development and integrates wonderfully with code editors like Visual Studio Code.

我们可以稍后讨论 TypeScript 的其他好处,现在让我们看一些例子!

¥We can talk about other TypeScript benefits later, let's see some examples now!

示例

¥Examples

看一下这个代码片段,然后我们可以一起解压它:

¥Take a look at this code snippet and then we can unpack it together:

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

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

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

const isJustineAnAdult: boolean = isAdult(justine);

第一部分(带有 type 关键字)负责声明代表用户的自定义对象类型。稍后我们利用这个新创建的类型来创建函数 isAdult,该函数接受一个 User 类型的参数并返回 boolean。此后,我们创建 justine,这是我们的示例数据,可用于调用先前定义的函数。最后,我们创建一个新变量,其中包含有关 justine 是否是成年人的信息。

¥The first part (with the type keyword) is responsible for declaring our custom object type representing users. Later we utilize this newly created type to create function isAdult that accepts one argument of type User and returns boolean. After this, we create justine, our example data that can be used for calling the previously defined function. Finally, we create a new variable with information on whether justine is an adult.

关于这个示例,你还应该知道其他一些事情。首先,如果我们不遵守声明的类型,TypeScript 会警告我们出现问题并防止滥用。其次,并非所有内容都必须明确输入 - TypeScript 非常智能,可以为我们推断类型。例如,即使我们没有明确输入变量 isJustineAnAdult,变量 isJustineAnAdult 的类型也将是 boolean;即使我们没有将此变量声明为 User 类型,justine 也是我们函数的有效参数。

¥There are additional things about this example that you should know. Firstly, if we would not comply with declared types, TypeScript would alarm us that something is wrong and prevent misuse. Secondly, not everything must be typed explicitly - TypeScript is very smart and can deduce types for us. For example, variable isJustineAnAdult would be of type boolean even if we didn't type it explicitly or justine would be valid argument for our function even if we didn't declare this variable as of User type.

好的,所以我们有一些 TypeScript 代码。现在我们如何运行它?

¥Okay, so we have some TypeScript code. Now how do we run it?

首先要做的是在我们的项目中安装 TypeScript:

¥First thing to do is to install TypeScript in our project:

npm i -D typescript

现在我们可以使用终端中的 tsc 命令将其编译为 JavaScript。让我们开始吧!

¥Now we can compile it to JavaScript using tsc command in the terminal. Let's do it!

假设我们的文件名为 example.ts,命令将如下所示:

¥Assuming that our file is named example.ts, the command would look like:

npx tsc example.ts

npx 代表 Node Package Execute。此工具允许我们运行 TypeScript 的编译器而无需全局安装它。

¥npx here stands for Node Package Execute. This tool allows us to run TypeScript's compiler without installing it globally.

tsc 是 TypeScript 编译器,它将获取我们的 TypeScript 代码并将其编译为 JavaScript。此命令将生成一个名为 example.js 的新文件,我们可以使用 Node.js 运行该文件。现在当我们知道如何编译和运行 TypeScript 代码时,让我们看看 TypeScript 的错误预防功能在起作用!

¥tsc is the TypeScript compiler which will take our TypeScript code and compile it to JavaScript. This command will result in a new file named example.js that we can run using Node.js. Now when we know how to compile and run TypeScript code let's see TypeScript bug-preventing capabilities in action!

这是我们将如何修改代码:

¥This is how we will modify our code:

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 对此的看法是:

¥And this is what TypeScript has to say about this:

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 成功阻止了我们交付可能意外运行的代码。太棒了!

¥As you can see TypeScript successfully prevents us from shipping code that could work unexpectedly. That's wonderful!

有关 TypeScript 的更多信息

¥More about TypeScript

TypeScript 提供了许多其他出色的机制,如接口、类、工具类型等。此外,在较大的项目中,你可以在单独的文件中声明 TypeScript 编译器配置,并精细地调整其工作方式、严格程度以及存储编译文件的位置等。你可以在 官方 TypeScript 文档 中阅读有关所有这些精彩内容的更多信息。

¥TypeScript offers a whole lot of other great mechanisms like interfaces, classes, utility types and so on. Also, on bigger projects you can declare your TypeScript compiler configuration in a separate file and granularly adjust how it works, how strict it is and where it stores compiled files for example. You can read more about all this awesome stuff in the official TypeScript docs.

值得一提的 TypeScript 的其他一些好处包括它可以逐步采用,有助于使代码更具可读性和可理解性,并且允许开发者在为旧版 Node.js 交付代码时使用现代语言功能。

¥Some of the other benefits of TypeScript that are worth mentioning are that it can be adopted progressively, it helps making code more readable and understandable and it allows developers to use modern language features while shipping code for older Node.js versions.

在 Node.js 中运行 TypeScript 代码

¥Running TypeScript Code in Node.js

Node.js 无法原生运行 TypeScript。你无法直接从命令行调用 node example.ts。但是这个问题有三种解决方案:

¥Node.js cannot run TypeScript natively. You cannot call node example.ts from the command line directly. But there are three solutions to this problem:

编译 TypeScript 到 JavaScript

¥Compiling TypeScript to JavaScript

如果你想在 Node.js 中运行 TypeScript 代码,你需要先将其编译为 JavaScript。你可以使用 TypeScript 编译器 tsc 执行此操作,如前所示。

¥If you want to run TypeScript code in Node.js, you need to compile it to JavaScript first. You can do this using the TypeScript compiler tsc as shown earlier.

这是一个小例子:

¥Here's a small example:

npx tsc example.ts
node example.js

使用 ts-node 运行 TypeScript 代码

¥Running TypeScript Code with ts-node

你可以使用 ts-node 直接在 Node.js 中运行 TypeScript 代码,而无需先编译它。但是它不是对你的代码进行类型检查。因此,我们建议在交付之前先使用 tsc 对代码进行类型检查,然后使用 ts-node 运行它。

¥You can use ts-node to run TypeScript code directly in Node.js without the need to compile it first. But it's not typechecking your code. So we recommend to type check your code first with tsc and then run it with ts-node before shipping it.

要使用 ts-node,你需要先安装它:

¥To use ts-node, you need to install it first:

npm i -D ts-node

然后你可以像这样运行你的 TypeScript 代码:

¥Then you can run your TypeScript code like this:

npx ts-node example.ts

使用 tsx 运行 TypeScript 代码

¥Running TypeScript Code with tsx

你可以使用 tsx 直接在 Node.js 中运行 TypeScript 代码,而无需先编译它。但是它不是对你的代码进行类型检查。因此,我们建议在交付之前先使用 tsc 对代码进行类型检查,然后使用 tsx 运行它。

¥You can use tsx to run TypeScript code directly in Node.js without the need to compile it first. But it's not typechecking your code. So we recommend to type check your code first with tsc and then run it with tsx before shipping it.

要使用 tsx,你需要先安装它:

¥To use tsx, you need to install it first:

npm i -D tsx

然后你可以像这样运行你的 TypeScript 代码:

¥Then you can run your TypeScript code like this:

npx tsx example.ts

如果你想通过 node 使用 tsx,你可以通过 --import 注册 tsx

¥If you want to use tsx via node, you can register tsx via --import:

node --import=tsx example.ts

Node.js 世界中的 TypeScript

¥TypeScript in the Node.js world

TypeScript 在 Node.js 世界中根深蒂固,被许多公司、开源项目、工具和框架使用。一些使用 TypeScript 的开源项目的著名示例包括:

¥TypeScript is well-established in the Node.js world and used by many companies, open-source projects, tools and frameworks. Some of the notable examples of open-source projects using TypeScript are:

  • NestJS - 强大且功能齐全的框架,使创建可扩展且架构良好的系统变得轻松愉快

    ¥NestJS - robust and fully-featured framework that makes creating scalable and well-architected systems easy and pleasant

  • TypeORM - 出色的 ORM,受到其他语言的其他知名工具(如 Hibernate、Doctrine 或 Entity Framework)的影响

    ¥TypeORM - great ORM influenced by other well-known tools from other languages like Hibernate, Doctrine or Entity Framework

  • Prisma - 下一代 ORM,具有声明性数据模型、生成的迁移和完全类型安全的数据库查询

    ¥Prisma - next-generation ORM featuring a declarative data model, generated migrations and fully type-safe database queries

  • RxJS - 广泛用于反应式编程的库

    ¥RxJS - widely used library for reactive programming

  • AdonisJS - 带有 Node.js 的功能齐全的 Web 框架

    ¥AdonisJS - A fully featured web framework with Node.js

  • FoalTs - 优雅的 Nodejs 框架

    ¥FoalTs - The Elegant Nodejs Framework

还有许多许多很棒的项目……甚至可能是你的下一个!

¥And many, many more great projects... Maybe even your next one!