It's all the rage these days in the world of web development - TypeScript.  I'd wager by now you have heard about it, even in passing.  But, if you haven't or if you're just curious then you've come to the right place my friend!

这些天来,Web开发领域( TypeScript)风靡一时。 到现在为止,我都会打赌您已经听说过它,即使顺带一提。 但是,如果您还没有,或者只是好奇,那么您来对地方了,我的朋友!

I'm currently learning TypeScript in conjunction with Angular (an article on this is in the works, so stay tuned!) because it's what our web application is built in at work.  I decided to write up something easy and simple to follow so you can get up and running with TypeScript data types.

我目前正在与Angular一起学习TypeScript(有关此文章的内容尚在研究中,敬请期待!),因为这是我们的Web应用程序在工作中内置的功能。 我决定编写一些易于遵循的内容,以便您可以使用TypeScript数据类型启动并运行它。

I'll break this article up into two posts for simplicity - the first will be a brief overview of what TypeScript is, the data types, and some supporting examples.  The second article will be focused on getting TypeScript installed and running locally on your machine.

为了简单起见,我将本文分为两篇文章-第一篇文章将简要概述什么是TypeScript,数据类型以及一些支持的示例。 第二篇文章将重点介绍如何在计算机上本地安装和运行TypeScript。

它是什么? (What Is It?)

Before we start, here's a super condensed description of TypeScript in my own words.  It's a superset of JavaScript - which essentially means it's a form of JavaScript that gives you certain benefits along with all of the greatness included in 'vanilla' JavaScript.  It's an open source language written and maintained by Microsoft.

在开始之前,这是我用自己的话简要描述TypeScript的过程。 它是JavaScript的超集 -从本质上讲 ,它是JavaScript的一种形式,可为您带来某些好处以及“原始” JavaScript中包含的所有功能。 这是一种由Microsoft编写和维护的开源语言。

TypeScript transpiles to JavaScript and will run in any environment that native JavaScript runs.  You may use TypeScript for both front end and back end applications.

TypeScript转换为JavaScript,并将在本机JavaScript运行的任何环境中运行。 您可以将TypeScript用于前端和后端应用程序。

It's written just like JavaScript, with a few exceptions that we'll go over soon.  Here's an example of some TypeScript:

它的写法与JavaScript相似,但有一些例外,我们将尽快进行讨论。 这是一些TypeScript的示例:

Try not to focus on all of the colons and extra stuff you see above, we'll dig into that below.  Instead, focus on the things that stand out - we're just declaring variables with values, these are strings, arrays, and objects just like in JavaScript.

尽量不要集中在上面看到的所有冒号和其他内容,我们将在下面进行深入探讨。 相反,请专注于突出的事物-我们只是在声明带有值的变量,就像在JavaScript中一样,它们是字符串,数组和对象。

Another great thing that I've learned about TypeScript is you can mix JavaScript in with the code and have no issues doing so.  Check the screenshot below (this is inside an Angular app):

我从TypeScript中学到的另一件事是,您可以将JavaScript与代码混合在一起,这样做没有问题。 检查以下屏幕截图(这是在Angular应用程序内):

资料类型 (Data Types)

Let's get started with the fun stuff - data types!  (There are a few data types we won't cover - never, null, undefined.  This is simply because there isn't much to them.  I want you to know they exist and if you'd like to dig in more on those types, here is a link to the official TypeScript documentation for your reference.)

让我们开始学习有趣的东西-数据类型! (有几种数据类型我们不会涉及-永不,空,未定义。这仅仅是因为它们没有太多。我想让您知道它们的存在,以及是否想进一步了解这些数据类型类型,以下是官方TypeScript文档的链接供您参考。)

TypeScript will infer the type of data assigned to a variable without you explicitly setting the type but for simplicity and good measure I like to declare the data type when declaring my variables.

TypeScript会推断出分配给变量的数据类型,而无需您显式设置类型,但是为了简便起见,我想在声明变量时声明数据类型。

We assign data types by simply placing a colon after the variable name but before the equal sign:

我们通过简单地在变量名之后但在等号之前放置一个冒号来分配数据类型:

const {variable name}: {variable type} = {variable value}

const {变量名称}:{变量类型} = {变量值 }

This is the convention that the majority of TypeScript data types are declared with the exception of functions and objects.

按照惯例,大多数TypeScript数据类型都声明为函数和对象除外。

Some data types come with a bit more complexity than that, but you get the general idea.  Below are some brief explanations of data types and examples of how to declare them.

某些数据类型的复杂性要比这复杂得多,但是您可以理解。 以下是数据类型的一些简要说明以及如何声明它们的示例。

布尔型 (Boolean)

Booleans in TypeScript work the same way as they do in JavaScript.  Variables of data type boolean are declared like so:

TypeScript中的布尔值的工作方式与JavaScript中的布尔值相同。 数据类型为boolean的变量声明如下:

const myBool: boolean = false;

const myBool: boolean = false ;

串 (String)

Strings in TypeScript work the same way as they do in JavaScript.  Variables of data type string are declared like so:

TypeScript中的字符串的工作方式与JavaScript中的字符串相同。 数据类型为string的变量声明如下:

let myString: string = 'bacon'

let myString: string = 'bacon'

数 (Number)

Numbers in TypeScript work the same way as they do in JavaScript.  Variables of data type number are declared like so:

TypeScript中的数字的工作方式与JavaScript中的数字相同。 声明数据类型为number的变量,如下所示:

const myNum: number = 1207;

const myNum: number = 1207;

数组 (Array)

Arrays in TypeScript are, like other data types, just like arrays in JavaScript.  Variables of data type array are declared two separate ways :

与其他数据类型一样,TypeScript中的数组与JavaScript中的数组一样。 声明数据类型数组的变量有两种方法:

const myArr: number[] = [12, 90, 71];

const myArr: number[] = [12, 90, 71];

The above way is how you'd declare an array if all of the elements inside that array are numbers.

上面的方法是如果该数组中的所有元素都是数字,则如何声明该数组。

const myArr: Array<number> = [12, 90, 71];

const myArr: Array<number> = [12, 90, 71];

This way of declaring an array uses the generic array type set to number.  Functionally, there is no difference in how these ways produce the end result of declaring a variable with array type.

这种声明数组的方式使用设置为number的通用数组类型。 从功能上讲,这些方式产生声明数组类型变量的最终结果的方式没有区别。

If the data types inside the array are unknown or a mixture of data types, the array can be declared using the <any> type (this is a type all on it's own that is discussed below):

如果数组内部的数据类型未知或混合使用,则可以使用<any>类型声明数组(这是一个单独的类型,下面将进行讨论):

const myArr: Array<any> = [12, 'thirteen', false];

const myArr: Array<any> = [12, 'thirteen', false];

This way will allow you to mix data types in the array.

这种方式将允许您混合数组中的数据类型。

元组 (Tuples)

Tuples are a data type unique to TypeScript.  Think of them as arrays with a fixed number of elements.  This data type is best used when you know exactly how many variables you should have.  It is possible to reassign the value of the indices but not the amount of elements in the tuple.

元组是TypeScript独有的数据类型。 可以将它们视为具有固定数量元素的数组。 当您确切知道应该有多少个变量时,最好使用此数据类型。 可以重新分配索引的值,但不能重新分配元组中元素的数量。

Variables of data type tuple are declared just like an array:

声明数据类型元组的变量就像数组一样:

let mine: [number, string];

let mine: [number, string];

If we'd like to change the values of elements, we can do that as long as they match the types we provided when declaring our variable:

如果我们想更改元素的 ,只要它们与声明变量时提供的类型匹配,我们就可以这样做:

mine[0] = 14  ✔️

mine[0] = 14 14✔️

mine[0] = 'Steve'

mine[0] = 'Steve' Steve'❌

Since we defined mine as a tuple, the order of the values matter as well and cannot be changed  Also, assigning an index outside of the original defined number will produce an error:

由于我们将mine定义为元组,因此值的顺序也很重要,并且无法更改。此外,在原始定义的数字之外分配索引也会产生错误:

mine[0] = ['Dave', 71]  ❌

mine[0] = ['Dave', 71]

mine = [121, 'Dave', 'Steve'];

mine = [121, 'Dave', 'Steve'];

mine = [121, 'bacon'];  ✔️

mine = [121, 'bacon']; ✔️

功能 (Function)

Functions can be as explicit as you want them to be.  What I mean by that is we can apply types to the parameters and returned values.  Below are two examples:

函数可以像您希望的那样明确。 我的意思是,我们可以将类型应用于参数和返回值。 以下是两个示例:

This function will throw an error if any value is returned that is not a number.  It may return a variable only if that variable points to a number.

如果返回的值不是数字,则此函数将引发错误仅当该变量指向数字时,它才可以返回该变量。

Above, we're type checking on the parameters being passed into our function.  This is a great way to avoid mistakes because if the number of parameters is off or if their data type doesn't match what we're expecting TypeScript will let us know with an error.

上面,我们正在对传递到函数中的参数进行类型检查。 这是避免错误的好方法,因为如果关闭了参数数量或它们的数据类型不匹配,我们期望TypeScript会在发生错误时通知我们。

If I want a function that should not return a value, I can set the type as void (a data type that means the absence of any data.  While it can be used when declaring variables it typically isn't because then we'd have to set the variable to null or undefined,  I've only used when functions should have no return value) and if the function returns anything TypeScript will throw an error:

如果我想要一个不应该返回值的函数,则可以将类型设置为void (一种数据类型,表示没有任何数据。虽然可以在声明变量时使用它,但通常不是,因为那样我们将变量设置为nullundefined ,我仅在函数不应该返回值时使用),并且如果函数返回任何内容,TypeScript将引发错误:

By setting the type to void I'm being explicit about my returns and establishing that while this function may still run, it should not return a value.  If it does return a value, I'll get an error.

通过将类型设置为void,我明确了自己的返回值,并确定该函数可能仍在运行,但不应返回值。 如果确实返回值,我将得到一个错误。

枚举 (Enum)

Enums are a welcomed (in my humble opinion) addition to the data types.  Think of them as a more user friendly approach to giving names to numeric values.  Here is an example of an enum:

在我看来,枚举是数据类型的一种受欢迎的补充。 将它们视为给数字值命名的更用户友好的方法。 这是一个枚举示例:

enum Foods {'bacon', 'tomato', 'lettuce'};

enum Foods {'bacon', 'tomato', 'lettuce'};

console.log(Foods[0]) // yields 'bacon' console.log(Foods.bacon) // yields 0  console.log(Foods['lettuce']) // yields 2

console.log(Foods [0])//产生'培根'console.log(Foods.bacon)//产生0 console.log(Foods ['lettuce'])//产生2

It's also possible to assign the numbering index format with enums as well.  Many languages including C# have enums and I'm happy to see them come to JavaScript.

也可以为枚举分配编号索引格式。 包括C#在内的许多语言都有枚举,我很高兴看到它们使用JavaScript。

You can be as creative as you want with the names.  You can even change the numeric representation of the indices.  If you want your first index to start at 18 instead of 0, it's as simple as:

您可以随心所欲地使用名称。 您甚至可以更改索引的数字表示。 如果您希望第一个索引从18开始而不是0,那么就很简单:

enum Foods {'bacon'= 18, 'tomato', 'lettuce'};

enum Foods {'bacon'= 18, 'tomato', 'lettuce'};

console.log(Foods['bacon']); // 18

console.log(Foods['bacon']); // 18

Let's say we had the value 18 but were unsure of what it mapped to in our Foods enum, we can check that as well:

假设我们的值是18,但是不确定它在Foods枚举中对应的是什么,我们也可以检查一下:

console.log(Foods[18]); // 'bacon'

console.log(Foods[18]); // 'bacon'

One piece of noteworthy information is now that we've set the first index to start at 18, the next index will be 19, and so on following the numbering convention you establish.

现在值得注意的一条信息是,我们将第一个索引设置为从18开始,下一个索引将设置为19,依此类推,遵循您建立的编号约定。

Object

目的

Objects in TypeScript are defined in similar ways as objects in JavaScript are defined.  We can be as implicit or explicit with our definition as we like or as the situation dictates:

TypeScript中的对象定义与JavaScript中的对象定义类似。 我们可以根据自己的喜好或情况的要求对定义进行隐式或显式的显示:

let data: = {name: 'Jonathan', age: 30, hobbies: ['running','swimming','coding']};  ✔️

let data: = {name: 'Jonathan', age: 30, hobbies: ['running','swimming','coding']}; ✔️

let data: {name: string, age: number, hobbies: string[]} = {name: 'Jonathan', age: 30, hobbies: ['running','swimming','coding']};  ✔️

let data: {name: string, age: number, hobbies: string[]} = {name: 'Jonathan', age: 30, hobbies: ['running','swimming','coding']}; ✔️

When creating objects, the property names are immutable, but the order in which they appear does not matter, even if we define them in a specific order.

创建对象时,属性名称是不可变的,但是即使我们以特定顺序定义它们,它们的出现顺序也没有关系。

Also, we can have simple objects like those above, or we can define complex objects that take advantage of multiple data types like the one below (this object is for demonstration purposes only):

同样,我们可以拥有像上述对象那样的简单对象,也可以定义利用多种数据类型的复杂对象,例如下面的对象(该对象仅用于演示目的):

类型别名/接口 (Type Alias/Interface)

With the example of a complex object above, you might be thinking this is awesome but what happens the next time I need to create a complex object?  I need to type all of this out manually again?

以上面的复杂对象为例,您可能会认为这很棒,但是下次我需要创建复杂对象时会发生什么呢? 我需要再次手动输入所有这些吗?

Fear not, the type alias and interface types are here to help!  A type alias is a data type that allows us to save other data types inside of it and then reference a variable instead of rewriting code over and over.

不用担心,这里的类型别名和接口类型可以为您提供帮助! 类型别名是一种数据类型,它允许我们在其中保存其他数据类型,然后引用变量,而不是一遍又一遍地重写代码。

As a side note, type aliases and interfaces work in very similar ways.  Both allow us to scaffold an object/blueprint for how our data should be structured.  However, there are subtle differences that we won't cover here.  Instead, here is a post that explains those differences in an extremely efficient fashion if you'd like to dig deeper.

附带说明,类型别名和接口的工作方式非常相似。 两者都允许我们为对象/蓝图搭建一个框架,说明数据的结构。 但是,这里有一些细微的差异 ,我们将不再介绍。 相反,如果您想更深入地了解,则这里的帖子以非常有效的方式解释了这些差异 。

There are details between the two that we should be aware of - when using the type alias, we use an equals sign (=) to declare values, the interface does not require an equal sign.

两者之间有一些我们需要注意的细节-使用类型别名时,我们使用等号(=)声明值,该接口不需要等号。

Now that we have our alias declared, it's time to make use of that alias.  When we want to "build" our new variable from this alias, we simply set it as the data type:

现在我们已经声明了别名,是时候使用该别名了。 当我们想从该别名“构建”新变量时,只需将其设置为数据类型:

It's important to note that the interface is specific to TypeScript.  It is used only at compile time to do type checking and to catch any errors that may have slipped past our watchful eye.  The data from our interface will end up in our final code, but the interface itself is compiled out.

请务必注意,该接口特定于TypeScript。 它仅在编译时使用,以进行类型检查并捕获可能已经超出我们注意范围的任何错误。 来自接口的数据将最终存储在我们的最终代码中,但是接口本身已被编译出来

Classes

班级

Classes are, in part, the veritable "bread and butter" of TypeScript (at least in my humble opinion).  Staying with this idea of scaffolding new objects, classes allow us to build data in a much easier way than just manually typing them out each time the need arises.

类在某种程度上是TypeScript的真正“面包和黄油”(至少在我看来是卑鄙的)。 保持这种构架新对象的想法,类使我们能够以比简单的在每次出现需求时手动将其键入的方式容易的方式构建数据。

Classes can be thought of as blueprints for how our data should be defined and what actions, if any, it should be capable of through methods.

可以将类视为如何定义我们的数据以及可以通过方法采取哪些行动(如有)的蓝图。

Below is an example of a class in TypeScript (which is made possible by the introduction of classes in ES6):

下面是TypeScript中的类的示例(通过在ES6中引入类成为可能):

Now, you might be asking yourself what are the differences between a class, a type alias, and an interface?  Great question!  The main difference between is that classes can be instantiated (we can create new instances of them) but an interface cannot.

现在,您可能会问自己, 类型别名接口之间有什么区别? 好问题! 两者之间的主要区别是可以实例化类(我们可以创建它们的新实例),但是接口不能实例化。

There are, of course, other differences but that's not contained in the scope of this article.  If you'd like to dig deeper, here is a great article I read to help me understand those differences.  You'll find use cases for all of them, as I have, when using TypeScript.

当然,还存在其他差异,但这不包含在本文的范围内。 如果您想深入研究,请阅读以下精彩文章,以帮助我理解这些差异。 使用TypeScript时,您将找到所有这些用例。

Union

联盟

This is, far and away, my favorite data type of TypeScript!  The union type allows us declare a variable and then set it to an "either or" value.  What I mean by that is let's say we're expecting data to be passed into a function but we aren't sure if it's a string or a number - this is the perfect (and intended) purpose of the union type.

这是我最喜欢的TypeScript数据类型! 联合类型允许我们声明一个变量,然后将其设置为“或”值。 我的意思是说我们期望将数据传递到函数中,但是我们不确定它是字符串还是数字-这是联合类型的完美(和预期)用途。

We use the single pipe character (on Windows it's Shift + the key right above Enter) when defining the type.  Here's what it would look like when defining a variable with union data type:

在定义类型时,我们使用单个管道字符(在Windows中为Shift + Enter上方的键)。 这是定义具有联合数据类型的变量时的外观:

const numOfDoors: string | string[ ];

const numOfDoors: string | string[ ];

This tells TypeScript that numOfDoors is a variable that can hold either a string or an array of strings.

这告诉TypeScript numOfDoors是一个可以容纳字符串或字符串数​​组的变量。

Here is an example of that function I mentioned earlier using union type:

这是我之前提到的使用联合类型的函数示例:

Any

任何

Any is the type we set whenever we're unsure of the types of data we'll be getting.  Maybe we're getting something from a third party or some dynamic data and we aren't 100% sure if we're getting a string, a number, or maybe an array of information.  This is the perfect use case for type any.

每当我们不确定要获取的数据类型时,任何类型就是我们设置的类型。 也许我们是从第三方或一些动态数据中获取信息,但我们不确定100%是否要获取字符串,数字或信息数组。 这是any类型的完美用例。

I will caution against using type any unless you absolutely must because when used we're opting out of one of the core features of TypeScript - type checking.

我会警告不要使用任何类型,除非您绝对必须使用,因为使用时我们选择退出TypeScript的核心功能之一-类型检查。

However, this data type has it's use cases just like all of the data types mentioned.

但是,与提到的所有数据类型一样,此数据类型具有用例。

这是一个包装! (That's A Wrap!)

I told you this wouldn't take too long :D

我告诉你这不会花太长时间:D

I hope you enjoyed this article about TypeScript and are exited about the how it can prove useful to your code base.  In the next article, we'll dig into the practical side of TypeScript.  We'll go over installing it, compiling, and using it in your project (not just Angular projects either)!

我希望您喜欢这篇有关TypeScript的文章,并且对如何证明它对您的代码库有用而退出了。 在下一篇文章中,我们将深入探讨TypeScript的实际方面。 我们将继续在您的项目(不仅是Angular项目)中安装,编译和使用它!

This was originally posted to my blog.

这最初发布到我的博客上 。

While you’re there don't forget to sign up for my Newsletter –   you can do that at the top right of the 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 this page.  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/learn-typescript-data-types-from-zero-to-hero/

学习TypeScript数据类型-从零到英雄相关推荐

  1. 零基础学习ruby_学习Ruby:从零到英雄

    零基础学习ruby "Ruby is simple in appearance, but is very complex inside, just like our human body.& ...

  2. 学习Python:从零到英雄

    首先,什么是Python?根据其创建者Guido van Rossum的说法,Python是: "高级编程语言及其核心设计哲学全都与代码可读性和一种语法有关,该语法使程序员可以用几行代码表达 ...

  3. 系统学习 TypeScript(四)——变量声明的初步学习

    前言 认识了 TypeScript 中的基础类型,接下来当然是变量声明的相关学习了. 声明多维数组 假如有这么一个声明: let arr3: number[][][]; 想要知道 arr3 的具体类型 ...

  4. 初学者怎么快速学习3D建模?零基础必备建模知识,你都明白吗?

    第一点,工具的使用不够熟练,甚至有些功能还不知道.很多初学者对软件不够熟悉,,很多的工具都还没用过,快捷键也还不知道,其实这些的解决方法很简单,就是多去练,多去问,然后多去记.熟能生巧,模型做多了,对 ...

  5. 三分钟快速了解typeScript数据类型

    前言: TypeScript 是由微软开发的一款开源的编程语言. TypeScript 是 Javascript 的超级,遵循最新的 ES6.ES5 规范 TypeScript 扩展了JavaScri ...

  6. 【HZHT001】黄子涵学习Typescript

    黄子涵学习Typescript Typescript语言概览 Typescript语言基础 变量 在计算机程序中,一个变量使用给定的符号名与内存中的某个存储地址相关联并且可以容纳某个值.变量的值可以在 ...

  7. boilerplate_完整的React Boilerplate教程-从零到英雄

    boilerplate by Leonardo Maldonado 莱昂纳多·马尔多纳多(Leonardo Maldonado) 完整的React Boilerplate教程-从零到英雄 (A Com ...

  8. 深入浅出学习 TypeScript 语言

    课程简介 2012年10月,微软发布了首个公开版本的 TypeScript,2013年6月19日,在经历了一个预览版之后微软发布了正式版 TypeScript 0.9.TypeScript 是 Jav ...

  9. 学习TypeScript(TS),这一篇就足够了

    一.TypeScript 简介 1.什么是 TypeScript? 官方文档 TypeScript 本质上是向 JavaScript 语言添加了「可选的静态类型」和「基于类的面向对象」编程,它相当于是 ...

最新文章

  1. criteria创建criteria 左连接 再 添加 add example,报错 ClassCastException:
  2. 学习是一个漫长不能松懈的过程
  3. 浪潮NF5270M3 刷uefi_新零售浪潮中,开为科技利用刷脸支付帮门店“运营”人
  4. c#如何判断字符串是否含中文
  5. Ubuntu下命令行cd进不了/home/用户目录
  6. linux mysql数据库日志关闭,linux 怎样恢復mysql数据库日志
  7. nuxt页面跳转_nuxt 项目如何解决组件复用时页面不刷新的问题
  8. 动态规划 —— 状压 DP
  9. 用手写一个工具的过程讲清楚Go反射的使用方法和应用场景
  10. 五十九、备战蓝桥杯 - Java算法 (基础练习一)
  11. 基于Python的指数基金量化投资 - 指数投资技巧(一)定期定额
  12. 高通QCA9531 2.4GHz电梯监控无线CPE
  13. HTTP性能测试工具siege
  14. 算法:如何判断两颗二叉树是否相等
  15. 半导体的基础-三极管的工作原理,史上绝无仅有的理解方式
  16. 简单几步搞定Mac电脑快速返回桌面的操作!
  17. [Spring Boot 6]企业级开发
  18. 高会职称计算机课程,高会职称计算机《Frontpage 2000网页制作》全部开通
  19. bootstrap 兼容ie8浏览器
  20. 编程练习6:最大公约数

热门文章

  1. MySQL中order by语句的实现原理以及优化手段
  2. 基于Java(SpringBoot)+Vue+MySQL 实现(Web)的网络课程平台【100010329】
  3. Python使用numpy获取列表行数、列数
  4. struts2标签和表单验证
  5. 辞职后五险一金怎么处理
  6. 零基础培训出来的人工资是多少?
  7. Java常用类————JDK8新增时间类
  8. 无线蓝牙耳机哪款好?2021年吃鸡游戏耳机推荐
  9. Oracle 正则 判断数字,oracle 判断是否数字 正则表达式法
  10. webpack Promis is undefine