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 包管理器)
  • 通过安装 TypeScript 的 Visual Studio 插件

Visual Studio 2017 和 Visual Studio 2015 更新 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

结果将是一个包含你输入的相同 JavaScript 的文件 greeter.js。 我们已经在我们的 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 提供的一些新工具。按照下面的示例,在 ‘person’ 函数参数上添加一个 : string 类型注解:

🌐 Now we can start taking advantage of some of the new tools TypeScript offers. Add a : string type annotation to the ‘person’ function parameter 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 函数以单个字符串参数调用。 我们可以尝试将调用 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 arguments. 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 parameters 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 中的类只是同样基于原型的面向对象(OO)语法的简写,这在 JavaScript 中经常使用。

🌐 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 网络应用!

🌐 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