TypeScript最大的好处是引入了静态类型检查,可减少书写错误。
安装采用Node的包管理工具npm:npm install -g typescript
TypeScript文件后缀名为ts,转换成普通js文件:tsc xxx.ts
1.定义变量、函数参数、函数返回值的时候可以指定类型
var a:string = "Hello world!";
var b:number = 2;
var c:boolean = true;
var d:null = null;
var e:undefined = undefined;
function fun():void {
console.log(1);
}
var f:any = 1; // any是任意类型
f = "abc";
2.一个变量可拥有多种类型,类型用竖线分隔
var a1:string | number = 1;
a1 = "hello world";
function fun1(param1:number) : boolean | number | string {
return 1;
}
3.数组类型
var arr1:number[] = [1, 2, 4]; // arr1内的成员必须是数字型
var arr2:string[] = ['a', 'b', 'c'];// arr2内的成员必须是字符型
4.定义函数类型
var fun:(a:string) => string;
fun = function(a:string):string {
return 'ok' + a;
}
interface obj {
fun1:(a:number)=>number
}
let obj1:obj = {
fun1:function(a:number):number {
return a + 10;
},
}
5.声明外部函数类型,方便ts文件中使用js函数
var fun:(string) => any;
declare var jQuery:(string) => any;
console.log(jQuery('#id'));
6.type类型别名
type val = string;
var a:val = 'abc'; // a只能是string型
type vals = 'a' | 'b';
var b:vals = 'a'; // b只能是'a'或者'b'
7.元组
var a1:[string, number] = ['a', 1]; // 元组
8.枚举
enum enum1{a, b, c};
console.log(enum1.a)
9.类、构造函数、子类
class Person {
name;
constructor(name, public age) {
this.name = name;
// 构造函数参数age前有public,则自动生成属性并赋值this.age = age;
}
print_() {
console.log("Person:" + this.name + "," + this.age);
}
}
class Man extends Person {
//...
}
10.get/set
class Man {
constructor() {
this.val = 'Man';
}
get name() {
return this.val;
}
set name(val) {
this.val = val;
}
}
11.public、private、protected
class Person {
public name;
protected age;
private tel;
//...
}
默认是public
12.抽象类
abstract class Bread {
constructor() {
}
public abstract way();
}
13.接口和类
interface Test2 {
say2();
}
interface Test3 extends Test2 { // 接口可以继承接口
say3();
}
class Man implements Test1, Test3 {
//...
}
14.声明合并
function f1(name:string):string;
function f1(name:any):any {
return "f1";
}
interface f2 {
say1();
}
interface f2 {
say2();
}
15.增强字符串,定义在撇号(``)内的字符串
// 字符串模板
var v1 = "aabb";
var fun1 = function ():string {
return "xxyy"
}
console.log(`${v1},${fun1()}`);
// 多行字符串
var content = `aaa
bbb
ccc`
16.函数参数可选,函数参数默认值
function fun1(param1: string, param2?: string, param3: string = 'wy') {
// 可选参数param2,带默认值的参数param3,需声明在普通参数后面
}
17.变长参数
function fun1(arg1, arg2, ...args) {
console.log(arg1 + "," + arg2);
args.forEach(arg => console.log(arg));
}
fun1('a', 'b', 'c' + 'd' + 'e');
18.从对象或数组中取值
var obj = {
code:"IBM",
price:100,
obj:{
me:'a',
tel:'123',
}
}
var {code, price:p, obj:{me}} = obj;
console.log(code + "," + p + "," + obj + "," + me);
var arr = ['a', 'b', 'c'];
var [num1, ,num2] = arr;
console.log(num1 + "," + num2);
19.箭头表达式
可避免一些this指针的问题
1: v => v + 1;
2: () => console.log('ok');
3: v => {
return console.log('ok' + v);
}
20.for of循环
var arr = [1, 2, 3];
for(var v of arr) {// 循环遍历数组
console.log(v);
}