安装typescript_如何安装和开始使用TypeScript

安装typescript

TypeScript is one of the current hot topics in web development, and for good reasons.

出于充分的原因,TypeScript是Web开发中当前的热门话题之一。

It allows us to type cast when declaring variables which means we explicitly set the type of data we expect back. Then it throws errors if the returned data is not the type we expected to get back, or if a function call has too few or too many arguments. And that's just a sampling of everything it offers.

它允许我们在声明变量时键入强制类型转换,这意味着我们显式设置了我们期望返回的数据类型。 如果返回的数据不是我们期望返回的类型,或者函数调用的参数太少或太多,那么它将引发错误。 那只是它提供的所有内容的样本。

If you'd like an overview of the data types you will find it helpful to read my previous article. Reading that article isn't required but it will give you a great understanding of the data types and syntax for TypeScript.

如果您需要数据类型的概述,那么阅读我以前的文章会对您有所帮助。 阅读该文章不是必需的,但是它将使您对TypeScript的数据类型和语法有很好的了解。

Before we start, it's important to note that TypeScript can be used in conjunction with a framework/library but it can also be used independent of a framework/library. TypeScript is the default in Angular projects and I have an article in the works about getting started with it.

在开始之前,重要的是要注意TypeScript可以与框架/库一起使用,但也可以独立于框架/库使用。 TypeScript是Angular项目中的默认设置,我在作品中有一篇有关入门的文章。

Also, this article assumes you have a basic understanding of JavaScript programming.

另外,本文假设您对JavaScript编程有基本的了解。

So, now we're ready to get started with TypeScript and start making use of its awesome features.

因此,现在我们准备开始使用TypeScript并开始使用它的强大功能。

Let's dig in!

让我们开始吧!

安装TypeScript (Installing TypeScript)

There are two main ways to install TypeScript.  The first is through Visual Studio (not to be confused with Visual Studio Code) which is an IDE.  The 2015, 2017, and I believe 2019 versions come with TypeScript installed already.

安装TypeScript有两种主要方法。 首先是通过Visual Studio (不要与Visual Studio Code混淆),它是一个IDE 。 我相信2015、2017和我相信2019版本已经安装了TypeScript。

This is not the route I'll be covering today since I mainly use Visual Studio Code for all of my needs.

因为我主要使用Visual Studio Code来满足我的所有需求,所以这不是我今天要讨论的路线。

The second way, and the way we'll focus on, is through NPM (Node Package Manager).

第二种方法以及我们将重点关注的方法是通过NPM (节点程序包管理器)。

If you don't already have NPM and/or Node installed (you get NPM when you install Node), now is a great time to do so as it's a requirement for the next steps (and by association a requirement to use TypeScript).

如果尚未安装NPM和/或Node (在安装Node时获得NPM),则现在是个不错的选择,因为这是后续步骤的要求(并关联使用TypeScript的要求)。

Once you have Node and NPM installed, open your terminal in VS Code and run the following command:

一旦安装了Node和NPM,就可以在VS Code中打开终端并运行以下命令:

npm install -g typescript

npm install -g typescript

Once it's finished installing, you'll see that 1 package has been added. You'll also see a message stating the version of TypeScript that was installed.

安装完成后,您会看到已添加1个软件包。 您还将看到一条消息,指出已安装的TypeScript版本。

This is everything you need to start compiling TypeScript to JavaScript.

这就是开始将TypeScript编译为JavaScript所需的一切。

Now you're ready to start writing TypeScript!

现在您可以开始编写TypeScript了!

启动TypeScript项目 (Starting A TypeScript Project)

Let's create a TypeScript project so we can take advantage of all those great features that come along with using it.

让我们创建一个TypeScript项目,以便我们可以利用使用它带来的所有出色功能。

In your editor of choice (I'm using VS Code) let's create an HTML file to be the visual side of our code.  Here's what my basic HTML file looks like:

在您选择的编辑器中(我使用VS Code),让我们创建一个HTML文件作为代码的直观外观。 这是我的基本HTML文件的样子:

Honestly, we're just using this HTML so we can have something to look at on the page. What we're really concerned with is using the console.

老实说,我们只是使用此HTML,因此我们可以在页面上看到一些内容。 我们真正关心的是使用控制台。

You'll notice I have app.js linked in the head of our index.html file.

您会注意到我的index.html文件的开头链接了app.js

You're probably saying to yourself I thought this was an article about TypeScript?

您可能对自己说, 我以为这是一篇有关TypeScript的文章?

Well hold your horses, it is. I just want to highlight some of the differences between JavaScript and TypeScript (You'll learn where this file comes from down below).

好吧,是的。 我只想强调JavaScript和TypeScript之间的一些区别(您将从下面了解此文件的位置)。

Below you'll see a simple variable declaration and a console log statement:

在下面,您将看到一个简单的变量声明和一个控制台日志语句:

As a side note, if you want to disable some ES-Lint rules you can place the rules at the top in comments like I've done above.  Or if you want to completely disable ES-Lint for that file only you can place /* eslint-disable */ at the top of the file.

附带说明一下,如果您想禁用某些ES-Lint规则,可以像上面我一样将规则放在注释的顶部。 或者,如果只想完全禁用该文件的ES-Lint,则可以在文件顶部放置/* eslint-disable */

And here is the browser console:

这是浏览器控制台:

Let's pretend that I'm building an application and for the userName I expect to always get a string back.  Along the way, I may make a mistake or my data may get mutated from another source.

让我们假设我正在构建一个应用程序,并且对于userName我希望总是返回一个字符串。 一路上,我可能会犯一个错误,或者我的数据可能会从另一个来源变异。

Now, userName is a number :(

现在, userName是一个数字:(

And here is the browser console showing the changes to userName that we likely didn't want to happen if this were a production application:

这是浏览器控制台,显示了如果是生产应用程序,我们可能不想发生的对userName的更改:

What if the returned userName was then passed into another function or used as a piece of a larger data puzzle?

如果返回的userName随后被传递到另一个函数或用作更大的数据难题,该怎么办?

It would not only be a mess to figure out where the mutation occurred (especially if we had a larger application), but also would create an untold number of bugs in our code.

弄清楚突变发生的位置(特别是如果我们有一个更大的应用程序)会很麻烦,而且还会在我们的代码中创建大量的错误。

Now, let's try that same experiment in TypeScript.  To do that, we'll need to create a new file with the .ts extension to denote a TypeScript file.

现在,让我们在TypeScript中尝试相同的实验。 为此,我们需要创建一个扩展名为.ts的新文件来表示TypeScript文件。

I'll name mine app.ts to stay consistent with naming conventions and put the same code from our JavaScript file into our new TypeScript file.

我将命名为app.ts以便与命名约定保持一致,并将来自我们JavaScript文件的相同代码放入我们的新TypeScript文件中。

You'll notice that I'm using type casting when declaring my variable now, and I'm explicitly telling TypeScript that this variable should point to a string value only.

您会注意到,现在声明变量时我正在使用类型转换,并且我明确告诉TypeScript该变量应仅指向字符串值。

You'll also notice that I have an error line under userName when I'm reassigning its value.

您还会注意到,当我重新分配其值时,在userName下有一条错误行。

使用CLI编译TypeScript (Compiling TypeScript With the CLI)

To see what this looks like in our console we have to compile it to JavaScript. We do that by running tsc app.ts in our VS Code console (you can also run the same command in any terminal as long as you're in the correct directory).

要查看控制台中的外观,我们必须将其编译为JavaScript。 我们可以通过在VS Code控制台中运行tsc app.ts来做到这一点(只要您在正确的目录中,也可以在任何终端中运行相同的命令)。

When we run this command it will compile our TypeScript into JavaScript. It'll also generate another file with the same name, only with a .js extension.

当我们运行此命令时,它将把TypeScript编译成JavaScript。 它还将生成另一个具有相同名称的文件,但扩展名为.js

This is where that app.js file came from that I mentioned earlier in the article.

这是我在本文前面提到的app.js文件的来源。

To compile multiple files at once, just provide those names in your command, one after the other: tsc app.ts header.component.ts

要一次编译多个文件,只需在命令中提供这些名称,一个接一个地提供: tsc app.ts header.component.ts

It's also possible to compile multiple TypeScript files into a single JavaScript file by adding the --out flag:

通过添加--out标志,也可以将多个TypeScript文件编译为一个JavaScript文件:

tsc *.ts --out index.js

tsc *.ts --out index.js

There’s also a watch command which will recompile all of the TypeScript automatically anytime a change is detected. This keeps you from having to run the same command over and over:

还有一个watch命令,只要检测到更改,它就会自动重新编译所有TypeScript。 这使您不必一遍又一遍地运行相同的命令:

tsc *.ts --out app.js --watch

tsc *.ts --out app.js --watch

Here's the output from that tsc app.ts command above:

这是上面的tsc app.ts命令的输出:

This error tells us that there's a problem with the reassignment of userName. Because we explicitly set our variable to be a string (even if I hadn't set the variable to a string the error would still occur because TypeScript infers data types) we cannot reassign it to a number.

此错误告诉我们, userName的重新分配存在问题。 因为我们将变量明确设置为字符串( 即使我没有将变量设置为字符串,但由于TypeScript推断数据类型,仍然会发生错误 ),因此无法将其重新分配给数字。

This is a great feature because it forces us to be explicit with our variable declarations and saves us from making mistakes that could prove annoying and time consuming. If you expect a particular type of data you should get that data, otherwise you should get an error.

这是一个很棒的功能,因为它迫使我们在变量声明中保持明确,并使我们避免犯可能会烦人且耗时的错误。 如果期望特定类型的数据,则应获取该数据,否则应获取错误。

使用显式声明的数组和对象 (Using Explicitly Declarative Arrays and Objects)

Let's say I'm building a project and instead of manually setting the navigation links, I want to store that info in an array of objects.

假设我正在构建一个项目,而不是手动设置导航链接,而是希望将该信息存储在对象数组中。

I'll expect a specific format for the information that's stored so it's consistent across all of the links.

我希望存储的信息采用特定的格式,以便在所有链接中保持一致。

Here's how I can set a "complex" array in TypeScript:

这是我可以在TypeScript中设置“复杂”数组的方法:

On the left side we declare the name of the variable navLinks, followed by a colon. At the curly braces is where we start declaring the format of the information we expect in this array.

在左侧,我们声明变量navLinks的名称,后跟一个冒号。 在花括号处,我们开始声明该数组中期望的信息格式。

We're telling TypeScript that we expect this array to contain an object or objects with these property names and types. We expect a name which is a string, a link which is a string, and an alt which is also a string.

我们告诉TypeScript我们希望该数组包含一个或多个具有这些属性名称和类型的对象。 我们期望一个name是一个字符串,一个link是一个字符串,以及一个alt也是一个字符串。

As with other data types, if we deviate from the format we established for this variable, we run into errors.

与其他数据类型一样 ,如果偏离为此变量建立的格式,则会遇到错误。

Here we tried to add a new entry that was blank and we got the following error:

在这里,我们尝试添加一个空白的新条目,并出现以下错误:

Type '{}' is missing the following properties from type '{ name: string; link: string; alt: string; }' : name, link, alt ts(2739)

Type '{}' is missing the following properties from type '{ name: string; link: string; alt: string; }' : name, link, alt ts(2739)

We get similar errors if we try to add another entry with the wrong type of information:

如果尝试添加信息类型错误的另一个条目,则会遇到类似的错误:

{ name: 'Jonathan', link: 15, alt: false }  ❌

{ name: 'Jonathan', link: 15, alt: false }

{ name: ['Jon','Marley'], link: `https://link123.net`, alt: null }  ❌

{ name: ['Jon','Marley'], link: `https://link123.net`, alt: null }

this.navLinks[0].img = '../../assets/img'

this.navLinks[0].img = '../../assets/img' ../assets/img'❌

this.navLinks[0].name = 'Barnaby'✔️

this.navLinks[0].name = 'Barnaby' Barnaby'✔️

You get the idea though. Once we establish the format, TypeScript will hold us to that format and inform us if/when we deviate from it with an error.

你明白了。 一旦我们建立了格式,TypeScript就会将我们保留为该格式,并在发生错误时告知我们是否/何时偏离该格式。

Also, here's a few ways to define an array:

另外,以下是定义数组的几种方法:

const arr1: Array = ['Dave', 35, true]; // will allow us to have any number of elements with any type

const arr1: Array = ['Dave', 35, true]; //将允许我们拥有任意数量的任何类型的元素

const people: [string,string,string] = ['John', 'Sammy', 'Stephanie']; // will throw an error if more than 3 strings or any non string elements appear in the array

const people: [string,string,string] = ['John', 'Sammy', 'Stephanie']; //如果数组中出现3个以上的字符串或任何非字符串元素,则会抛出错误

const people: Array = ['Jimmy', 'Theresa', 'Stanley']; //will allow us to have any number of only string elements in our array

const people: Array = ['Jimmy', 'Theresa', 'Stanley']; //将允许我们在数组中具有任意数量的唯一字符串元素

Objects work much the same way as arrays do in TypeScript. They can be explicitly defined with set types or you can let TypeScript do all the inferring. Here's a basic example of an object:

对象的工作方式与TypeScript中的数组相同。 可以使用集合类型显式定义它们,也可以让TypeScript进行所有推断。 这是一个对象的基本示例:

const person: {name:string, address: string, age: number} = {name: 'Willy', address: '123 Sunshine Ln', age: 35}

const person: {name:string, address: string, age: number} = {name: 'Willy', address: '123 Sunshine Ln', age: 35}

Again, on the left side we're declaring person as the variable name with the first set of curly braces defining the format we want our data to be in.

同样,在左侧,我们将person声明为变量名,并使用第一组花括号定义了我们希望数据使用的格式。

It is important to note that in objects, the order we define our properties in does not have to match the order of the format:

重要的是要注意,在对象中,我们定义属性的顺序不必与格式的顺序匹配:

函数,参数和参数 (Functions, Parameters & Arguments)

Some of the greatest benefits you'll see in TypeScript come when using functions.

使用函数时,您会在TypeScript中看到一些最大的好处。

Have you ever built a function to do a specific task only to find out it's not working as you intended?

您是否曾经构建过一个功能来执行特定任务,只是发现它未按预期工作?

While using TypeScript it won't be because you didn't get/send the correct type of data or use the correct number of parameters/arguments.

使用TypeScript时,不会因为您没有获得/发送正确的数据类型或使用正确数量的参数/参数而导致。

Here's a great example:

这是一个很好的例子:

In our function we expect to receive 3 arguments when calculator executes. However, if we receive the wrong number of arguments (too few or too many) TypeScript will give us a nice error:

在我们的函数中,我们希望在calculator执行时会收到3个参数。 但是,如果我们收到错误数量的参数(太少或太多),TypeScript将给我们带来一个不错的错误:

Likewise, if we receive the wrong type of data when executing this function TypeScript will generate an error and the function will not run.

同样,如果执行此函数时收到错误的数据类型,TypeScript将生成错误,并且该函数将无法运行。

calculator('12', '11', 'add) ;

calculator('12', '11', 'add) ;

Now you may be saying to yourself 'So what? That's all well and good but it doesn't seem like that's a huge deal.' But imagine that your application is dozens and dozens of files with many layers of abstractions.

现在您可能对自己说: “那又如何? 一切都很好,但似乎并没有什么大不了的。” 但是,请想象您的应用程序是具有多层抽象层的数十个文件。

A great example of this would be an Angular application with services, data models, multilevel components, and all the dependencies that go along with that. It becomes increasingly difficult to pinpoint where an error is coming from when your application gets to be large.

一个很好的例子是带有服务,数据模型,多级组件以及所有相关性的Angular应用程序。 查明应用程序变大时错误的出处变得越来越困难。

就这样 (That's All)

Hopefully you can see the benefits of TypeScript now. There are plenty more than those I have outlined here and I encourage you to read the documentation if you want to find more.

希望您现在可以看到TypeScript的好处。 除了我在此处概述的内容以外,还有很多其他内容。如果您想了解更多信息,建议您阅读文档。

You can find this article and others like it on my blog. I'd love for you to stop by!

您可以在我的博客中找到本文和其他类似文章 。 我希望你能停下来!

While you’re there why not sign up for my Newsletter  –  you can do that at the top right of the main blog page. I promise I’ll never spam your inbox and your information will not be shared with anyone/site. I like to occasionally send out interesting resources I find, articles about web development, and a list of my newest posts.

当您在那里时,为什么不注册我的时事通讯 –您可以在博客主页面的右上角进行操作。 我保证我永远不会向您的收件箱发送垃圾邮件,并且不会与任何人/站点共享您的信息。 我偶尔会发送一些有趣的资源,有关Web开发的文章以及最新文章列表。

If you haven’t yet, you can also connect with me on social media! All of my links are also at the top right of that page as well. I love connecting with others and meeting new people so don’t afraid to say hi.

如果您还没有,也可以在社交媒体上与我联系! 我所有的链接也都在该页面的右上方。 我喜欢与他人联系并结识新朋友,所以不要害怕打招呼。

Have an awesome day, friend, and happy coding!

祝您有个美好的一天,朋友和愉快的编码!

翻译自: https://www.freecodecamp.org/news/how-to-install-and-begin-using-typescript/

安装typescript

你可能感兴趣的:(python,java,javascript,大数据,编程语言)