5 分钟了解 TypeScript 工具

让我们开始使用 TypeScript 构建一个简单的 Web 应用。

¥Let’s get started by building a simple web application with TypeScript.

安装 TypeScript

¥Installing TypeScript

将 TypeScript 添加到项目中的方法主要有两种:

¥There are two main ways to add TypeScript to your project:

  • 通过 npm(Node.js 包管理器)

    ¥Via npm (the Node.js package manager)

  • 通过安装 TypeScript 的 Visual Studio 插件

    ¥By installing TypeScript’s Visual Studio plugins

Visual Studio 2017 和 Visual Studio 2015 Update 3 默认包含 TypeScript 语言支持,但不包含 TypeScript 编译器 tsc。如果你没有用 Visual Studio 安装 TypeScript,你仍然可以 下载它

¥Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript language support by default but does not include the TypeScript compiler, tsc. If you didn’t install TypeScript with Visual Studio, you can still download it.

对于 npm 用户:

¥For npm users:

shell
> npm install -g typescript

构建你的第一个 TypeScript 文件

¥Building your first TypeScript file

在你的编辑器中,在 greeter.ts 中键入以下 JavaScript 代码:

¥In your editor, type the following JavaScript code in greeter.ts:

ts
function greeter(person) {
return "Hello, " + person;
}
 
let user = "Jane User";
 
document.body.textContent = greeter(user);
Try

编译你的代码

¥Compiling your code

我们使用了 .ts 扩展,但这段代码只是 JavaScript。你可以直接从现有的 JavaScript 应用中复制/粘贴它。

¥We used a .ts extension, but this code is just JavaScript. You could have copy/pasted this straight out of an existing JavaScript app.

在命令行中,运行 TypeScript 编译器:

¥At the command line, run the TypeScript compiler:

shell
tsc greeter.ts

结果将是一个文件 greeter.js,其中包含与你输入的相同的 JavaScript。我们已经在我们的 JavaScript 应用中使用 TypeScript 启动并运行了!

¥The result will be a file greeter.js which contains the same JavaScript that you fed in. We’re up and running using TypeScript in our JavaScript app!

现在我们可以开始利用 TypeScript 提供的一些新工具了。将 : string 类型注释添加到 ‘person’ 函数参数,如下所示:

¥Now we can start taking advantage of some of the new tools TypeScript offers. Add a : string type annotation to the ‘person’ function argument as shown here:

ts
function greeter(person: string) {
return "Hello, " + person;
}
 
let user = "Jane User";
 
document.body.textContent = greeter(user);
Try

类型注解

¥Type annotations

TypeScript 中的类型注释是记录函数或变量预期契约的轻量级方法。在这种情况下,我们打算使用单个字符串参数调用 greeter 函数。我们可以尝试更改调用欢迎程序以传递一个数组:

¥Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. In this case, we intend the greeter function to be called with a single string parameter. We can try changing the call greeter to pass an array instead:

ts
function greeter(person: string) {
return "Hello, " + person;
}
 
let user = [0, 1, 2];
 
document.body.textContent = greeter(user);
Argument of type 'number[]' is not assignable to parameter of type 'string'.2345Argument of type 'number[]' is not assignable to parameter of type 'string'.
Try

重新编译,你现在会看到一个错误:

¥Re-compiling, you’ll now see an error:

shell
error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

同样,尝试删除 greeter 调用的所有参数。TypeScript 将让你知道你已使用意外数量的参数调用此函数。在这两种情况下,TypeScript 都可以根据你的代码结构和你提供的类型注释提供静态分析。

¥Similarly, try removing all the arguments to the greeter call. TypeScript will let you know that you have called this function with an unexpected number of parameters. In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide.

请注意,尽管存在错误,但仍会创建 greeter.js 文件。即使你的代码中存在错误,你也可以使用 TypeScript。但在这种情况下,TypeScript 会警告你的代码可能不会按预期运行。

¥Notice that although there were errors, the greeter.js file is still created. You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.

接口

¥Interfaces

让我们进一步开发我们的示例。这里我们使用一个接口来描述具有 firstName 和 lastName 字段的对象。在 TypeScript 中,如果两种类型的内部结构兼容,则它们是兼容的。这允许我们仅通过具有接口所需的形状来实现接口,而无需显式的 implements 子句。

¥Let’s develop our sample further. Here we use an interface that describes objects that have a firstName and lastName field. In TypeScript, two types are compatible if their internal structure is compatible. This allows us to implement an interface just by having the shape the interface requires, without an explicit implements clause.

ts
interface Person {
firstName: string;
lastName: string;
}
 
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
 
let user = { firstName: "Jane", lastName: "User" };
 
document.body.textContent = greeter(user);
Try

¥Classes

最后,让我们用类最后一次扩展示例。TypeScript 支持 JavaScript 中的新功能,例如支持基于类的面向对象编程。

¥Finally, let’s extend the example one last time with classes. TypeScript supports new features in JavaScript, like support for class-based object-oriented programming.

在这里,我们将创建一个带有构造函数和一些公共字段的 Student 类。请注意,类和接口可以很好地协同工作,让程序员决定正确的抽象级别。

¥Here we’re going to create a Student class with a constructor and a few public fields. Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction.

同样值得注意的是,在构造函数的参数上使用 public 是一种简写形式,它允许我们自动创建具有该名称的属性。

¥Also of note, the use of public on arguments to the constructor is a shorthand that allows us to automatically create properties with that name.

ts
class Student {
fullName: string;
constructor(
public firstName: string,
public middleInitial: string,
public lastName: string
) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}
 
interface Person {
firstName: string;
lastName: string;
}
 
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
 
let user = new Student("Jane", "M.", "User");
 
document.body.textContent = greeter(user);
Try

重新运行 tsc greeter.ts,你会看到生成的 JavaScript 与之前的代码相同。TypeScript 中的类只是 JavaScript 中经常使用的基于原型的 OO 的简写。

¥Re-run tsc greeter.ts and you’ll see the generated JavaScript is the same as the earlier code. Classes in TypeScript are just a shorthand for the same prototype-based OO that is frequently used in JavaScript.

运行你的 TypeScript 网络应用

¥Running your TypeScript web app

现在在 greeter.html 中键入以下内容:

¥Now type the following in greeter.html:

html
<!DOCTYPE html>
<html>
<head>
<title>TypeScript Greeter</title>
</head>
<body>
<script src="greeter.js"></script>
</body>
</html>

在浏览器中打开 greeter.html 以运行你的第一个简单的 TypeScript Web 应用!

¥Open greeter.html in the browser to run your first simple TypeScript web application!

可选的:在 Visual Studio 中打开 greeter.ts,或将代码复制到 TypeScript playground。你可以将鼠标悬停在标识符上以查看它们的类型。请注意,在某些情况下,这些类型是自动为你推断的。重新输入最后一行,并根据 DOM 元素的类型查看完成列表和参数帮助。将光标放在对 greeter 函数的引用上,然后按 F12 转到它的定义。还要注意,你可以右键单击一个符号并使用重构来重命名它。

¥Optional: Open greeter.ts in Visual Studio, or copy the code into the TypeScript playground. You can hover over identifiers to see their types. Notice that in some cases these types are inferred automatically for you. Re-type the last line, and see completion lists and parameter help based on the types of the DOM elements. Put your cursor on the reference to the greeter function, and hit F12 to go to its definition. Notice, too, that you can right-click on a symbol and use refactoring to rename it.

提供的类型信息与工具一起工作,以在应用规模上使用 JavaScript。有关 TypeScript 的更多示例,请参阅网站的示例部分。

¥The type information provided works together with the tools to work with JavaScript at application scale. For more examples of what’s possible in TypeScript, see the Samples section of the website.

Visual Studio picture