5分钟内学习TypeScript-初学者教程

TypeScript is a typed superset of JavaScript, aimed at making the language more scalable and reliable.

TypeScript是JavaScript的类型化超集,旨在使语言更具扩展性和可靠性。

It’s open-source and has been maintained by Microsoft since they created it in 2012. However, TypeScript got its initial breakthrough as the core programming language in Angular 2. It’s been continuing to grow ever since, also in the React and Vue communities.

它是开源的,自2012年由Microsoft创建以来一直由Microsoft维护。但是,TypeScript作为Angular 2的核心编程语言取得了最初的突破。此后,它一直在持续增长,在React和Vue社区中也是如此。

In this tutorial, you’ll learn the basics of TypeScript with the help of practical examples.

在本教程中,您将在实际示例的基础上学习TypeScript的基础。

We are also about to launch a free 22-part TypeScript course on Scrimba. Leave your email here if you want early access!

我们还将在Scrimba上推出由22部分组成的免费TypeScript课程。 如果您想提早访问,请在此处留下您的电子邮件!

Let’s get started.

让我们开始吧。

安装TypeScript (Installing TypeScript)

Before we start coding, we need to install TypeScript on our computer. We’ll use npm for this, so just open the terminal and type the following command:

在开始编码之前,我们需要在计算机上安装TypeScript。 我们将使用npm ,因此只需打开终端并输入以下命令:

npm install -g typescript

Once it is installed, we can verify it by running the command tsc -v which will display the version of the TypeScript installed.

安装完成后,我们可以通过运行命令tsc -v进行验证,该命令将显示已安装的TypeScript的版本。

编写一些代码 (Writing some code)

Let’s create our first TypeScript file and write some code inside it. Open up your favourite IDE or Text Editor and create a file with the name of first.ts — For TypeScript files, we use the extension.ts

让我们创建第一个TypeScript文件并在其中写入一些代码。 打开您喜欢的IDE或文本编辑器并创建一个名为first.ts文件-对于TypeScript文件,我们使用扩展名.ts

For now, we’re just going to write a few lines of plain old JavaScript, as all JavaScript code also is valid TypeScript code:

现在,我们将只编写几行普通的旧JavaScript,因为所有JavaScript代码也是有效的TypeScript代码:

let a = 5;  
let b = 5;  
let c = a + b;

console.log(c);

The next step is to compile our TypeScript into plain JavaScript, as browsers want .js files to read.

下一步是将TypeScript编译为纯JavaScript,因为浏览器希望读取.js文件。

编译TypeScript (Compiling TypeScript)

To compile, we’ll run the command of tsc filename.ts, which creates a JavaScript file with the same filename but a different extension, and which we eventually can pass on to our browsers.

要进行编译,我们将运行tsc filename.ts命令,该命令将创建一个具有相同文件名但具有不同扩展名JavaScript文件,并最终将其传递给我们的浏览器。

So open up the terminal at the location of the file and run the following command:

因此,在文件位置打开终端并运行以下命令:

tsc first.ts

Tip: If you want to compile all the TypeScript files inside any folder, use the command: tsc *.ts

提示 :如果要编译任何文件夹中的所有TypeScript文件,请使用以下命令: tsc *.ts

资料类型 (Data types)

TypeScript — as its name suggests — is the typed version of JavaScript. This means we can specify types to different variables at the time of declaration. They will always hold the same type of data in that scope.

顾名思义,TypeScript是JavaScript的类型化版本。 这意味着我们可以在声明时为不同的变量指定类型。 它们将在该范围内始终保存相同类型的数据。

Typing is a very useful feature to ensure reliability and scalability. Type checking helps to ensure our code works as expected. Also, it helps in hunting down bugs and errors and properly documenting our code.

键入是确保可靠性和可伸缩性的非常有用的功能。 类型检查有助于确保我们的代码按预期工作。 此外,它还有助于查找错误和错误并正确记录我们的代码。

The syntax to assign a type to any variable is to write the name of the variable followed by a : sign, and then the name of the type followed by a = sign and the value of the variable.

将类型分配给任何变量的语法是先写变量名,后跟:符号,然后写类型名,后跟=符号和变量值。

There are three different types in TypeScript: the any type, the Built-in types, and the User-defined types. Let’s have a look at each of them.

TypeScript中有三种不同的类型: any类型, Built-in类型和User-defined类型。 让我们看看它们中的每一个。

任何类型 (any type)

The any data type is the superset of all the data types in TypeScript. Giving any variable the type of any is equivalent to opting out of type checking for a variable.

any数据类型是TypeScript中所有数据类型的超集。 给予任何变量的类型any等同于用于可变类型检查的停用。

let myVariable: any = 'This is a string'
内置类型 (Built-in types)

These are the types which are built in TypeScript. They include number, string, boolean, void, null and undefined.

这些是在TypeScript中内置的类型。 它们包括numberstringbooleanvoidnullundefined

let num: number = 5;  
let name: string = 'Alex';  
let isPresent: boolean = true;
用户定义类型 (User-defined types)

The User-defined types include enum, class, interface, array, and tuple. We will discuss some of these later in this article.

User-defined类型包括enumclassinterfacearraytuple 。 我们将在本文后面讨论其中一些内容。

面向对象编程 (Object-oriented programming)

TypeScript supports all the features of object-oriented programming, such as classes and interfaces. This capability is a huge boost to JavaScript — it has always been struggling with its OOP functionality, especially since developers started using it for large scale applications.

TypeScript支持面向对象编程的所有功能,例如类和接口。 此功能极大地增强了JavaScript —一直以来,OOP功能一直在苦苦挣扎,特别是自开发人员开始将其用于大规模应用程序以来。

(Class)

In object-oriented programming, a class is the template of objects. A class defines how an object would look like in terms of that object’s features and functionalities. A class also encapsulates data for the object.

在面向对象的编程中,类是对象的模板。 类根据对象的特征和功能定义对象的外观。 类还封装对象的数据。

TypeScript has built-in support for classes, which were unsupported by ES5 and earlier versions. This means we can use the class keyword to easily declare one.

TypeScript具有对类的内置支持,ES5和更早版本不支持这些类。 这意味着我们可以使用class关键字轻松声明一个。

class Car {

// fields  
  model: String;  
  doors: Number;  
  isElectric: Boolean;

constructor(model: String, doors: Number, isElectric: Boolean) {  
    this.model = model;  
    this.doors = doors;  
    this.isElectric = isElectric;  
  }

displayMake(): void {  
    console.log(`This car is ${this.model}`);  
  }

}

In the above example, we have declared a Car class, along with some of its properties, which we’re initializing in the constructor. We also have a method which would display some message using its property.

在上面的示例中,我们声明了Car类及其一些属性,这些属性将在constructor函数中初始化。 我们还有一个方法,可以使用其属性显示一些消息。

Let’s see how we can create a new instance of this class:

让我们看看如何创建此类的新实例:

const Prius = new Car('Prius', 4, true);  
Prius.displayMake(); // This car is Prius

To create an object of a class, we use the keyword of new and call the constructor of the class and pass it the properties. Now this object Prius has its own properties of model, doors, and isElectric. The object also can call the method of displayMake, which would have access to the properties of Prius.

要创建类的对象,我们使用关键字new并调用类的构造函数并将其传递给属性。 现在,此对象Prius具有其自身的modeldoorsisElectric属性。 该对象还可以调用displayMake方法,该方法可以访问Prius的属性。

接口 (Interface)

The concept of interfaces is another powerful feature of TypeScript, which allows you to define the structure of variables. An interface is like a syntactical contract to which an object should conform.

接口的概念是TypeScript的另一个强大功能,它使您可以定义变量的结构。 接口就像对象应遵循的语法约定。

Interfaces are best described through an actual example. So, suppose we have an object of Car:

最好通过一个实际示例来描述接口。 因此,假设我们有一个Car对象:

const Car = {  
  model: 'Prius',  
  make: 'Toyota',  
  display() => { console.log('hi'); }  
}

If we look at the object above and try to extract its signature, it would be:

如果我们查看上面的对象并尝试提取其签名,则可能是:

{  
  model: String,  
  make: String,  
  display(): void  
}

If we want to reuse this signature, we can declare it in the form of an interface. To create an interface, we use the keyword interface.

如果要重用此签名,可以以接口的形式声明它。 要创建接口,我们使用关键字interface

interface ICar {  
  model: String,  
  make: String,  
  display(): void  
}

const Car: ICar = {  
  model: 'Prius',  
  make: 'Toyota',  
  display() => { console.log('hi'); }  
}

Here, we’ve declared an interface called ICar , and created an object Car. Car is now binding to the ICar interface, ensuring that the Car object defines all the properties which are in the interface.

在这里,我们声明了一个名为ICar的接口,并创建了一个Car对象。 Car现在绑定到ICar接口,确保Car对象定义了接口中的所有属性。

结论 (Conclusion)

So I hope this gave you a quick glimpse into how TypeScript can make your JavaScript more stable and less prone to bugs.

因此,我希望这能使您快速了解TypeScript如何使您JavaScript更加稳定并且不易出错。

TypeScript is gaining a lot of momentum in the world of web development. There’s also an increasing amount of React developers who are adopting it. TypeScript is definitely something any front-end developer in 2018 should be aware of.

TypeScript在Web开发领域正获得大量动力。 越来越多的React开发人员正在采用它。 TypeScript绝对是2018年任何前端开发人员都应该注意的事情。

Happy coding :)

快乐的编码:)



Thanks for reading! My name is Per Borgen, I'm the co-founder of Scrimba – the easiest way to learn to code. You should check out our responsive web design bootcamp if want to learn to build modern website on a professional level.

谢谢阅读! 我叫Per Borgen,我是Scrimba的共同创始人–学习编码的最简单方法。 如果要学习以专业水平构建现代网站,则应查看我们的响应式Web设计新手训练营

翻译自: https://www.freecodecamp.org/news/learn-typescript-in-5-minutes-13eda868daeb/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值