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 由什么组成?
¥What does TypeScript consist of?
TypeScript 由两个主要组件组成:代码本身和类型定义。
¥TypeScript consists of two main components: the code itself and type definitions.
TypeScript 代码
¥TypeScript Code
代码部分是常规 JavaScript,带有用于类型注释的附加 TypeScript 特定语法。编译 TypeScript 代码时,所有特定于 TypeScript 的部分都将被删除,从而生成可以在任何环境中运行的干净 JavaScript。例如:
¥The code part is regular JavaScript with additional TypeScript-specific syntax for type annotations. When TypeScript code is compiled, all the TypeScript-specific parts are removed, resulting in clean JavaScript that can run in any environment. For example:
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
类型定义
¥Type Definitions
类型定义描述了现有 JavaScript 代码的形状。它们通常存储在 .d.ts
文件中,不包含任何实际实现 - 它们只描述类型。这些定义对于与 JavaScript 的互操作性至关重要:代码通常不以 TypeScript 的形式分发,而是转换为包含 sidecar 类型定义文件的 JavaScript。
¥Type definitions describe the shape of existing JavaScript code. They are usually stored in .d.ts
files and don't contain any actual implementation—they only describe the types. These definitions are essential for interoperability with JavaScript: code is not usually distributed as TypeScript, but instead transpiled to JavaScript that includes sidecar type definition files.
例如,当你将 Node.js 与 TypeScript 结合使用时,你将需要 Node.js API 的类型定义。这可通过 @types/node
获得。使用以下方式安装:
¥For example, when you use Node.js with TypeScript, you'll need type definitions for Node.js APIs. This is available via @types/node
. Install it using:
npm add --save-dev @types/node
这些类型定义允许 TypeScript 理解 Node.js API,并在你使用 fs.readFile
或 http.createServer
等函数时提供适当的类型检查和自动补齐。例如:
¥These type definitions allow TypeScript to understand Node.js APIs and provide proper type checking and autocompletion when you use functions like fs.readFile
or http.createServer
. For example:
import * as fs from 'fs';
fs.readFile('example.txt', 'foo', (err, data) => {
// ^^^ Argument of type '"foo"' is not assignable to parameter of type …
if (err) throw err;
console.log(data);
});
许多流行的 JavaScript 库的类型定义都在 @types
命名空间下可用,由 DefinitelyTyped 社区维护。这可以将现有的 JavaScript 库与 TypeScript 项目无缝集成。
¥Many popular JavaScript libraries have their type definitions available under the @types
namespace, maintained by the DefinitelyTyped community. This enables seamless integration of existing JavaScript libraries with TypeScript projects.
转换功能
¥Transform Capabilities
TypeScript 还包括强大的转换功能,特别是对于 JSX(用于 React 和类似框架)。TypeScript 编译器可以将 JSX 语法转换为常规 JavaScript,类似于 Babel 的工作方式。虽然我们不会在这些文章中介绍这些转换功能,但值得注意的是,TypeScript 不仅是类型检查工具,它还是将现代 JavaScript 语法转换为适用于不同环境的兼容版本的构建工具。
¥TypeScript also includes powerful transformation capabilities, particularly for JSX (used in React and similar frameworks). The TypeScript compiler can transform JSX syntax into regular JavaScript, similar to how Babel works. While we won't cover these transformation features in these articles, it's worth noting that TypeScript isn't only a tool for type checking—it's also a build tool for transforming modern JavaScript syntax into compatible versions for different environments.
如何运行 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.