TypeScript Tutorial

 
 

Because work with TypeScript, pumping time, to introduce some basic knowledge of general and complete learning or recommendations from the official website tutorial, play happy

Universal browser supports JavaScript, and dynamic type features are ideal for general-purpose Web language. However, any developer of object-oriented backgrounds from all know, as applications become larger and larger, JavaScript flexibility may become a burden . This is Microsoft created TypeScript to help developers take advantage of a better reason to generate JavaScript object-oriented programming principles.

In this article, we will describe in detail the contents of TypeScript, and show you how to start using it.

什么是TypeScript?
TypeScript的好处
第1部分)安装和设置
第2部分)编译为JavaScript
第3部分)静态打字
第4部分)数组
第5部分)接口
第6部分)课程
第7部分)泛型
第8部分)模块和命名空间
第9部分)第三方声明文件

What is TypeScript?

TypeScript is called a superset of JavaScript . It is not a substitute for JavaScript, it will not add any new functionality to the JavaScript code. Instead, typescript in its code allows the programmer to use object-oriented configuration, and then convert it to JavaScript. It also includes type safety and compile-time type checking and other convenience features. Most importantly, it is completely free and open source.

TypeScript 2.3 is the latest version as of mid-2017 the language. If you are already familiar superset but no longer in circulation, TypeScript 2.0 introduces some major improvements, including more comprehensive error trapping and access statement files directly through npm install.

Although TypeScript is developed by Microsoft, and is the Visual Studio (IDE software) as standard, but it can be used in any environment. This tutorial will provide you with TypeScript Web development project, the tools needed to generate JavaScript code.

TypeScript use a variety of benefits, some of which include:

1.静态类型,TypeScript代码比JavaScript 更容易预测且更容易调试。
2. 面向对象的功能(如模块和命名空间)使组织大型代码库更易于管理。
3. 编译步骤在到达运行时之前捕获错误。
4. 流行的框架Angular是用TypeScript编写的。虽然您也可以在Angular中使用常规JavaScript,但您在框架中找到的大多数教程都是用TypeScript编写的。任何想要充分利用Angular和类似开发平台的人都会更好地了解TypeScript。
5. TypeScript类似于CoffeeScript,另一种编译为JavaScript的语言,但由于静态类型,前者比后者更灵活。

Part 1) Installation and setup

Visual Studio 2017 has been equipped with TypeScript plug-in, which is included in Visual Studio 2015 Update of 3. If you are using an older version of Visual Studio or any other environment, you can get TypeScript source code and install it as a Node.js package:

npm install -g typescript

After installation, you can start making TypeScript file and add it to an existing application. By *.ts扩展名识别TypeScript文件. TypeScript whenever you save a file, Visual Studio plug-in automatically generates a corresponding JavaScript file with the same name, for use. Each time you create a new TypeScript project, you will notice app.ts also generate a file that contains the default code implementation.

Visual Studio provides a wonderful view side by side for the corresponding TypeScript and JavaScript files. Whenever you save TypeScript, you can immediately see the changes in JavaScript.

This is you codepen.io similar time. Use CodePen, you can write TypeScript code and then view the compiled JavaScript. The following are some of the side by side comparison CodePen not compiled TypeScript and compiled JavaScript code.

 
image.png

Examples of this TypeScript tutorial assumes that you are using Visual Studio, but several other IDE and text editor TypeScript also provide support, including auto-complete suggestions, error trapping and built-in compiler.WebStorm,Vim,Atom,Emacs和Sublime Text都有TypeScript的内置支持或插件。

Part 2) compiler for JavaScript.

Since .ts files can not be used directly in the browser, so they must be compiled into regular JavaScript, this can be achieved in several ways. In addition to using an IDE or automated tasks such as running outside Gulp, the easiest way is to use the command-line tool TSC, as follows:

tsc index.ts

The above command will give you a file named index.js. If .js file with that name already exists, the file will be overwritten.

也可以通过简单地列出它们来一次编译多个文件:

tsc index.ts main.ts 

您可以.ts使用以下命令编译当前文件夹中的所有文件,但请记住它不能递归地工作:

tsc * .ts

要在对文件进行更改时自动编译,您可以设置观察程序进程:

tsc index.ts  -  watch 

如果你在与许多大型项目的工作.ts文件,它可能有助于创建一个tsconfig.json文件。您可以在TypeScript文档中阅读有关配置文件的更多信息。

第3部分)静态类型

TypeScript的定义功能是将它与JavaScript和CoffeeScript分开,它是静态类型,它允许您声明变量类型。编译器确保为变量分配正确的值类型,并且如果省略类型声明,它甚至可以进行推断。

除了“数字”,“布尔”和“字符串”等几种原始类型之外,您还可以使用名为“any”的动态类型。“Any”类似于C#中的“dynamic”关键字,因为它允许您为变量分配任何类型的值。因此,TypeScript不会标记“任何”变量的类型错误。

变量在TypeScript中声明的方式与它们在JavaScript中的方式相同。您可以通过添加冒号和类型名称来声明类型:

var num:number = 45;

在上面的示例中,变量num已分配类型“number”。您可以阅读TypeScript文档中的所有可用数据类型。

第4部分)数组

使用TypeScript,您可以使用括号创建数组:

var array:string [] = ['dog','cat'];
var first:string = array [0]; 

上面的TypeScript会给你以下JavaScript:

var array = ['dog','cat'];
var first = array [0]; 

如您所见,使用从零开始的索引访问TypeScript中的数组。您还可以使用基本类型构建复杂变量:

var name = {firstName:'Steve',lastName:'Jobs'};

即使您没有像上例中那样明确地为变量指定类型,TypeScript也会推断出“name”是一个带有字符串变量的复杂对象。如果您稍后将任何字符串以外的任何内容分配给这些变量中的任何一个,则会出现设计时错误。

第5部分)接口

定义接口允许您检查变量组合以确保它们使用一致。接口不会转换为JavaScript; 他们唯一的目的是帮助开发者。例如,您可以使用以下属性和类型定义接口:

interface Food {
    name: string;
    calories: number;
}

然后,您可以告诉函数期望适合“Food”界面的对象,以确保始终可以使用正确的属性:

function speak(food: Food): void { console.log("This " + food.name + " contains " + food.calories + " calories."); } 

现在,当您定义一个具有“Food”接口所需的所有属性的对象时,将自动推断出类型。如果TypeScript怀疑您犯了错误,编译器会通知您。例如,请使用以下代码:

var cherry_pie = {
    name: "cherry pie",
    caloreis: 500 } 

在上面的示例中,我们的某个属性拼写错误,因此您应该会收到如下错误消息:

main.ts(16,7): error TS2345: Argument of type '{ name: string; caloreis: number; }
is not assignable to parameter of type 'Food'.
Property 'calories' is missing in type '{ name: string; caloreis: number; }'. 

只要存在所需属性且类型正确,属性顺序无关紧要; 如果不是这种情况,您将收到编译器的警告,如上所述。

第6部分)类

TypeScript中的类与其他面向对象语言中的类大致相同。自ECMAScript 2015更新发布以来,类现在也是JavaScript的原生类,但类的规则在TypeScript中更严格一些。

您可以创建一个简单的TypeScript类,如下所示:

class Menu {
    items: Array<string>
    pages: number;
}

默认情况下,属性是公共的,但可以将它们设为私有。一旦建立了一些类,就可以设置构造函数来简化创建新对象的过程。

您也可以将一起使用的小的类(如Point,Size和Rectangle)组合到一个文件中,而不是为每个类提供自己的文件。尝试将这些组合类保留在150行代码下以避免任何问题。

第7部分)泛型

使用不同类型的变量时,设置泛型可能会有所帮助。泛型是可重用的模板,允许单个函数接受不同类型的参数。由于泛型保留类型,因此该技术优于过度使用“任何”类型变量。

看一下下面的脚本,它接收一个参数并返回一个包含相同参数的数组。函数名后面的“T”表示通用名称。调用该函数时,所有“T”实例将被提供的类型替换:

function genericFunc<T>(argument: T): T[] {
    var arrayOfT: T[] = [];
    arrayOfT.push(argument);
    return arrayOfT;
}

var arrayFromString = genericFunc<string>("beep");
console.log(arrayFromString[0]); console.log(typeof arrayFromString[0]) var arrayFromNumber = genericFunc(45); console.log(arrayFromNumber[0]); console.log(typeof arrayFromNumber[0]) 

在上面的示例中,当我们第一次调用函数时,手动将类型设置为字符串。此步骤不是必需的,因为编译器知道哪个参数已被传递,并且可以在下次调用函数时推断出哪种类型是合适的。

即使它不是必需的,但是养成在编译器出错时始终提供类型的习惯是很好的,这可能会随着代码变得更复杂而发生。将泛型与接口相结合实际上可以保证生成的JavaScript完美无瑕。

第8部分)模块和命名空间

模块提供了另一种组织和合并代码的方法。如果有效使用,将代码拆分为可重用组件可以减少项目的文件数量,从而使维护更加容易。在TypeScript中,内部模块称为“名称空间”,而外部模块称为模块。

TypeScript具有导出和导入模块的特殊语法; 但是,语言不能直接处理文件之间的连线,所以我们需要一些第三方库来方便外部模块的使用。具体来说,我们请使用RequireJS为浏览器的应用程序或CommonJS的对Node.js的。

想象一下,您正在使用浏览器应用程序,并且您有两个.ts文件:一个用于导出功能; 另一个用于导入和调用该函数。它们看起来如下:

exporter.ts

var sayHi = function(): void { console.log("Hello!"); } export = sayHi; importer.ts import sayHi = require('./exporter'); sayHi(); 

现在,要实现您的模块,首先需要下载require.js并将其粘贴到脚本标记上。然后,您必须设置一个额外的参数,让TypeScript知道您正在使用require.js,其操作如下:

tsc --module amd * .ts

学习如何在TypeScript中使用模块需要时间,但收益是巨大的。您可以在模块上的TypeScript文档中阅读有关它们的更多信息。

第9部分)第三方声明文件

当您需要使用最初用于常规JavaScript的库时,必须应用声明文件以使其与TypeScript兼容。具有扩展名的声明文件包含.d.ts有关库及其API的信息。您可以手动制作自己的声明文件,但您可以轻松找到.d.ts其他人已经创建的任何库的文件。

最好看的地方是DefinitelyTyped,这是一个庞大的公共存储库,拥有数千个库。当你在那里时,你也可以选择Typings,一个方便的Node.js模块来管理你的TypeScript定义。

TypeScript教程摘要

使用TypeScript几乎总是比直接编写JavaScript更好。即使您对JavaScript完全熟悉,花些时间学习TypeScript也会让您成为更快,更高效的Web开发人员。但是,TypeScript并不是唯一的“替代”JavaScript语言。其他受欢迎的选择包括CoffeeScript(如前所述),Babel、Elm。



作者:HowardHuang
链接:https://www.jianshu.com/p/70a03e21936c
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

Guess you like

Origin www.cnblogs.com/telwanggs/p/10954071.html