TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Let’s break down what exactly this means:
TypeScript是JavaScript的类型化超集,可编译为普通JavaScript。 让我们解释一下这到底是什么意思:
typed - You can define variable, parameter, and return data types.
类型化 -您可以定义变量,参数和返回数据类型。
superset - TypeScript adds some additional features on top of JavaScript. All valid JavaScript is valid TypeScript, but not the other way around.
超集 -TypeScript在JavaScript之上添加了一些附加功能。 所有有效JavaScript都是有效的TypeScript,但反之则不是。
compiles to plain JavaScript - TypeScript cannot be run by the browser. So available tooling takes care of compiling your TypeScript to JavaScript for the browser to understand.
编译为纯JavaScript -TypeScript无法由浏览器运行。 因此,可用的工具需要将您的TypeScript编译为JavaScript,以供浏览器理解。
In this tutorial you will work with TypeScript in Visual Studio Code to explore the benefits of using them together.
在本教程中,您将使用Visual Studio Code中的TypeScript来探索将它们一起使用的好处。
For this project, you will need:
对于此项目,您将需要:
A working understanding of JavaScript. You can review the How to Code in JavaScript series for more information.
对JavaScript有一定的了解。 您可以查看“ 如何在JavaScript中编码”系列以获取更多信息。
Node.js installed locally, which you can do by following How to Install Node.js and Create a Local Development Environment.
Node.js在本地安装,您可以按照如何安装Node.js和创建本地开发环境进行操作 。
Visual Studio Code (VS Code) downloaded and installled.
已下载并安装Visual Studio代码 (VS代码)。
The first step toward working with TypeScript is to install the package globally on your computer. Install the typescript
package globally by running the following command in your terminal:
使用TypeScript的第一步是在计算机上全局安装软件包。 通过在终端中运行以下命令来全局安装typescript
软件包:
Next, run the following command to make a project directory:
接下来,运行以下命令以创建项目目录:
mkdir typescript_test
mkdir typescript_test
Move into the newly created directory:
移至新创建的目录:
cd typescript_test
cd typescript_test
Now, you need to create a new TypeScript file. For reference, these end with the .ts
extension type.
现在,您需要创建一个新的TypeScript文件。 作为参考,这些文件以.ts
扩展名结尾。
You can now open up VS Code and create a new file by clicking File and then New File. After that, save it by clicking File and then Save As…. You can name this file app.ts
to follow this tutorial. The filename is not important, but ensuring the filetype extension of .ts
is.
现在,您可以打开VS Code并通过依次单击File和New File创建一个新文件。 之后,单击“ 文件” ,然后单击“ 另存为...”将其保存 。 您可以将此文件app .ts
命名为app .ts
以遵循本教程。 文件名并不重要,但是确保.ts
的文件类型扩展名很重要。
The first line of this file should start with an export {};
for VS Code to recognize it as a module.
该文件的第一行应以export {};
开头export {};
让VS Code将其识别为模块。
Create a function that will print the first and last name from a person
object:
创建一个将打印person
对象的名字和姓氏的函数:
export {};
function welcomePerson(person) {
console.log(`Hey ${person.firstName} ${person.lastName}`);
return `Hey ${person.firstName} ${person.lastName}`;
}
const james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
The problem with the code above is that there is no restriction on what can be passed to the welcomePerson
function. In TypeScript, you can create interfaces that define what properties an object should have.
上面的代码的问题在于,对可以传递给welcomePerson
函数的内容没有任何限制。 在TypeScript中,您可以创建定义对象应具有的属性的接口 。
In the snippet below, there is an interface for a Person
object with two properties, firstName
and lastName
. Then, the welcomePerson
function was modified to accept only Person
objects.
在下面的代码段中,有一个Person
对象的接口,该接口具有两个属性firstName
和lastName
。 然后,将welcomePerson
函数修改为仅接受Person
对象。
export {};
function welcomePerson(person: Person) {
console.log(`Hey ${person.firstName} ${person.lastName}`);
return `Hey ${person.firstName} ${person.lastName}`;
}
const james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
interface Person {
firstName: string;
lastName: string;
}
The benefit of this will become clear if you try to pass a string into the welcomePerson
function.
如果您尝试将字符串传递给welcomePerson
函数,则这样做的好处将变得很明显。
For example, replacing james
:
例如,更换james
:
welcomePerson(james);
With 'James'
:
与'James'
:
welcomePerson('James');
Because we are working with a TypeScript file, VS Code will immediately provide you feedback letting you know that the function expects a Person
object and not a string.
因为我们正在处理TypeScript文件,所以VS Code将立即为您提供反馈,让您知道该函数需要使用Person
对象而不是字符串。
Now that you have a working TypeScript file, you can compile it to JavaScript. To do this you need to call the function and tell it which file to compile. You can utlize the built-in terminal in VS Code to do this.
现在您有了一个有效的TypeScript文件,您可以将其编译为JavaScript。 为此,您需要调用该函数并告诉它要编译哪个文件。 您可以使用VS Code中的内置终端来执行此操作。
tsc app.ts
tsc 应用程式 .ts
If you didn’t fix the error before, you’ll see an error output:
如果您之前没有解决错误,则会看到错误输出:
app.ts:13:15 - error TS2345: Argument of type '"James"' is not assignable to parameter of type 'Person'.
app .ts:13:15-错误TS2345:“ James”类型的参数无法分配给“ Person”类型的参数。
Fix the error by passing the Person
object in correctly instead of a string. Then compile again, and you’ll get a valid JavaScript file.
通过正确传入Person
对象而不是字符串来解决错误。 然后再次编译,您将获得一个有效JavaScript文件。
Running an ls
command in the terminal will display the files in our current path:
在终端中运行ls
命令将在当前路径中显示文件:
ls
You will see your original ts
file and also a new js
file:
您将看到原始的ts
文件和一个新的js
文件:
app.js
应用程式 .js
app.ts
应用程式 .ts
Now, let’s open the app.js
file in VS Code.
现在,让我们在VS Code中打开app .js
文件。
"use strict";
exports.__esModule = true;
function welcomePerson(person) {
console.log("Hey " + person.firstName + " " + person.lastName);
return "Hey " + person.firstName + " " + person.lastName;
}
var james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
Notice that the template literal strings, which are an ES6 feature, were compiled to simple string concatenation from ES5. We’ll come back to this shortly.
注意, 模板文字字符串是ES6的功能,已从ES5编译为简单的字符串连接。 我们将稍后再讨论。
To verify that this worked, you can now run the JavaScript directly using Node in your terminal:
为了验证此方法是否有效,您现在可以在终端中直接使用Node运行JavaScript:
node app.js
节点应用 .js
You will see a name printed to the console:
您将看到一个打印到控制台的名称:
So far, you’ve compiled one file directly. This is great, but in a real world project, you might want to customize how all files are compiled. For instance, you might want to have them be compiled to ES6 instead of ES5. To do this, you need to create a TypeScript configuration file.
到目前为止,您已经直接编译了一个文件。 这很好,但是在现实世界的项目中,您可能需要自定义所有文件的编译方式。 例如,您可能希望将它们编译为ES6,而不是ES5。 为此,您需要创建一个TypeScript配置文件。
To create a TypeScript configuration file, you can run the following command (similar to an npm init
):
要创建TypeScript配置文件,可以运行以下命令(类似于npm init
):
You will receive this output:
您将收到以下输出:
Open your new tsconfig.json
file and you’ll see lots of different options, most of which are commented out.
打开新的tsconfig.json
文件,您将看到很多不同的选项,其中大多数已被注释掉。
You might have noticed there is a setting called "target"
which is set to "es5"
. Change that setting to "es6"
.
您可能已经注意到有一个名为"target"
的设置,该设置设置为"es5"
。 将该设置更改为"es6"
。
With these changes made to tsconfig.json
, run tsc
in your terminal:
对tsconfig.json
以下更改tsconfig.json
,在终端中运行tsc
:
Note: Unlike before, you are not specifying an input file. The official documentation points out: “When input files are specified on the command line, tsconfig.json
files are ignored.”
注意:与以前不同,您没有指定输入文件。 官方文档指出:“在命令行上指定输入文件时,将忽略tsconfig.json
文件。”
Now, open up the newly created JavaScript file:
现在,打开新创建JavaScript文件:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function welcomePerson(person) {
console.log(`Hey ${person.firstName} ${person.lastName}`);
return `Hey ${person.firstName} ${person.lastName}`;
}
const james = {
firstName: "James",
lastName: "Quick"
};
welcomePerson(james);
Notice that the template literal string was left alone, proving that your TypeScript was compiled successfully to ES6.
注意,模板文字字符串被保留了下来,证明您的TypeScript已成功编译到ES6。
Another thing you can change is where your JavaScript files are stored after being created. This setting can be specificed in "outDir"
.
您可以更改的另一件事是创建JavaScript文件后将其存储在何处。 可以在"outDir"
此设置。
Try deleting "outDir"
, and then start typing it in again. VS Code is providing you IntelliSense for which properties you can set in a TypeScript config file.
尝试删除"outDir"
,然后再次开始输入。 VS Code为您提供了IntelliSense ,您可以在TypeScript配置文件中为其设置属性。
You can change your "outDir"
from the current directory to a dist
directory like so:
您可以将"outDir"
从当前目录更改为dist
目录,如下所示:
"outDir": "./dist"
After compiling again (tsc
), notice that your output JavaScript file is indeed located inside of a dist
directory.
再次编译( tsc
)后,请注意您的输出JavaScript文件确实位于dist
目录中。
You can use the cd
and ls
commands in your terminal to explore the contents of the dist
directory:
您可以在终端中使用cd
和ls
命令来浏览dist
目录的内容:
You will see your compiled JavaScript file in the new location:
您将在新位置看到已编译JavaScript文件:
app.js
应用程式 .js
TypeScript has gained more and more popularity over the last couple of years. Here’s a couple of examples of how it is used in modern front-end frameworks.
在过去的几年中,TypeScript越来越受欢迎。 这是在现代前端框架中如何使用它的几个示例。
Angular CLI projects come preconfigured with TypeScript. All of the configuration, linting, etc. is built in by default. Create an Angular CLI project and take a look around. This is a great way to see what TypeScript looks like in a real app.
Angular CLI项目预先配置了TypeScript。 默认情况下,所有配置,棉绒等均内置。 创建一个Angular CLI项目并浏览一下。 这是查看真实应用中TypeScript外观的好方法。
Create React App doesn’t come with TypeScript by default, but with the latest version, it can be configured that way. If you’re interested in learning how to use TypeScript with Create React App, check out the [Using Create React App v2 and TypeScript]([https://www.digitalocean.com/community/tutorials/using-create-react-app-v2-and-typescript) article.
默认情况下,Create React App不随TypeScript一起提供,但对于最新版本,可以通过这种方式进行配置。 如果您有兴趣学习如何将TypeScript与Create React App一起使用,请查看[使用Create React App v2和TypeScript]([ https://www.digitalocean.com/community/tutorials/using-create-react- app-v2-and-typescript )文章。
Vue CLI projects can be configured to use TypeScript when creating a new project. For more details, you can check out the Vue Docs.
可以将Vue CLI项目配置为在创建新项目时使用TypeScript。 有关更多详细信息,您可以查看Vue Docs 。
In this tutorial, you explored using TypeScript with VS Code. TypeScript allows you to generate higher quality JavaScript that can provide more confidence when shipping to production. As you can tell, VS Code is well equipped to help you write TypeScript, generate configurations, and so on.
在本教程中,您探索了将TypeScript与VS Code结合使用的方法。 TypeScript允许您生成更高质量JavaScript,从而可以在交付生产时提供更大的信心。 如您所知,VS Code具备完善的功能,可以帮助您编写TypeScript,生成配置等。
翻译自: https://www.digitalocean.com/community/tutorials/how-to-work-with-typescript-in-visual-studio-code