如何在Visual Studio Code中使用TypeScript

介绍 (Introduction)

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来探索将它们一起使用的好处。

先决条件 (Prerequisites)

For this project, you will need:

对于此项目,您将需要:

第1步-安装和编译TypeScript (Step 1 — Installing and Compiling TypeScript)

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软件包:

  • npm install -g typescript

    npm install -g打字稿

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并通过依次单击FileNew 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对象的名字和姓氏的函数:

app.ts
应用程序
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对象的接口,该接口具有两个属性firstNamelastName 。 然后,将welcomePerson函数修改为仅接受Person对象。

app.ts
应用程序
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对象而不是字符串。

Output
输出量
  • Argument of type '"James"' is not assignable to parameter of type 'Person'.

    “ James”类型的参数不能分配给“ 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:

如果您之前没有解决错误,则会看到错误输出:

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文件:

Output
输出量
  • app.js

    应用程式 .js

  • app.ts

    应用程式 .ts

Now, let’s open the app.js file in VS Code.

现在,让我们在VS Code中打开app .js文件。

app.js
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:

您将看到一个打印到控制台的名称:

Output
输出量
  • Hey James Quick

    嘿詹姆斯·Quick

第2步-创建TypeScript配置文件 (Step 2 — Creating a TypeScript Config File)

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 ):

  • tsc --init

    tsc --init

You will receive this output:

您将收到以下输出:

Output
输出量
  • message TS6071: Successfully created a tsconfig.json file.

    消息TS6071:成功创建了tsconfig.json文件。

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

  • tsc

    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文件:

app.js
app.js
"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目录,如下所示:

tsconfig.json
tsconfig.json
"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:

您可以在终端中使用cdls命令来浏览dist目录的内容:

  • cd dist

    光盘
  • ls

    ls

You will see your compiled JavaScript file in the new location:

您将在新位置看到已编译JavaScript文件:

Output
输出量
  • app.js

    应用程式 .js

第3步-探索现代前端框架中的TypeScript (Step 3 — Exploring TypeScript in Modern Front-End Frameworks)

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越来越受欢迎。 这是在现代前端框架中如何使用它的几个示例。

角度CLI (Angular CLI)

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外观的好方法。

创建React App 2 (Create React App 2)

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 3 (Vue CLI 3)

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

结论 (Conclusion)

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值