TypeScript 简介

¥Introduction to TypeScript

什么是 TypeScript

¥What is TypeScript

TypeScript 是一种由 Microsoft 维护和开发的开源语言。

¥TypeScript is an open-source language maintained and developed by Microsoft.

基本上,TypeScript 为 JavaScript 添加了额外的语法,以支持与编辑器更紧密的集成。尽早在你的编辑器或 CI/CD 管道中捕获错误,并编写更易于维护的代码。

¥Basically, TypeScript adds additional syntax to JavaScript to support a tighter integration with your editor. Catch errors early in your editor or in your CI/CD pipeline, and write more maintainable code.

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

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

第一个 TypeScript 代码

¥First TypeScript code

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

¥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 = {
  name: 'Justine',
  age: 23,
} satisfies User;

const isJustineAnAdult = 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 的类型也是 boolean,即使我们没有将此变量声明为 User 类型,justine 也是我们函数的有效参数。

¥There are additional things about this example that you should know. Firstly, if we do not comply with the declared types, TypeScript will inform us that something is wrong and prevent misuse. Secondly, not everything must be typed explicitly—TypeScript infers types for us. For example, the variable isJustineAnAdult is of type boolean even if we didn't type it explicitly, and justine would be a valid argument for our function even though we didn't declare this variable as of User type.

如何运行 TypeScript 代码

¥How to run TypeScript code

好的,所以我们有一些 TypeScript 代码。现在我们如何运行它?运行 TypeScript 代码的可能方法很少,我们将在下一篇文章中介绍所有这些方法。

¥Okay, so we have some TypeScript code. Now how do we run it? There are few possible ways to run TypeScript code, we will cover all of them in the next articles.