Typescript 是Angular2+ 的默认语言,是十分强大的,所以才吸引我去了解这门语言。可以说是以后端的代码逻辑去写前端代码。非常适合对后端开发比较熟悉的人。
本文章是慕课网的免费课程 TypeScript入门
TypeScript也有中文文档支持了 https://www.tslang.cn/docs/handbook/basic-types.html
搭建TyoeScript开发环境
首先TypeScript代码是需要转换成JavaScript代码才能被浏览器识别的,这就需要一个转换器compiler。而网上已经有在线的compiler了。可以打开http://www.typescriptlang.org/play/index.html
在本地开发的话可以使用npm安装
$ sudo npm install -g typescript
/usr/local/bin/tsc -> /usr/local/lib/node_modules/typescript/bin/tsc
/usr/local/bin/tsserver -> /usr/local/lib/node_modules/typescript/bin/tsserver
+ typescript@3.4.5
added 1 package from 1 contributor in 7.756s
安装完成后使用tsc命令即可
随后的演示还是用在线compiler。
TypeScript语法
字符串
在TS中,可以使用双``号定义多行字符串。也有字符串模板

自动拆分字符串是指将传进来的参数自动拆分为几分,直接看代码吧

运行结果如下

参数
默认参数 主要是给方法中变量一个默认值。可选参数 是可有可无的。

Rest and Spread操作符
这个就可以实现传入多个参数, 其中第二个ts虽然报错,但是翻译成js是可以运行的。

generator函数
控制函数的执行过程,手动暂停和恢复代码的执行。
https://www.babeljs.cn/repl
每次执行一次next,就会卡在yield。直到再次调用next。

下面这个例子是获取数字,从死循环中获取0-100之间的数,当小于15就退出,并打印出该数。

结果
the generator return 53.39674691940568
VM109:47 the generator return 33.892917606982856
VM109:47 the generator return 82.93371248164996
VM109:47 the generator return 7.755429359104737
VM109:49 buying at 7.755429359104737
destructuring析构表达式
通过表达式将对象或数组拆解成任意数量的变量。

获取嵌套对象中的某个数据

数组中的析构表达式

析构表达式作为方法参数

箭头函数
这是es6的高级表达式,十分简单,还可以消除令人混乱的_this = this 这种表达式(this关键字)。

消除this关键字带来的问题。

可以看下输出。IBM是没有输出的,而Google是有的
name is :Google
name is :
name is :Google
name is :
name is :Google
循环表达式
-
forEach
-
for in
-
for of
循环
类Class (面向对象编程)
简单的类的声明,默认类内的每一个属性和方法都是public的,在外部和内部都能访问。而private是只允许类的内部

类的构造函数 constructor ,在类被声明后默认直接执行且只执行一次。

类的继承 extends
super 去初始化一下父类。

泛型genic
其实就是指定在数组中放什么样的类型,在前面的例子展示过很多此了,这就是泛型

接口interface
用来建立某种代码约定,使得其他的开发者在调用某个方法或创建新的类时必须遵循接口所定义的代码类型。
比如最简单的例子

再比如声明方法,就必须在类里面实现这个方法,不实现的话会报错。

网友评论