TypeScript是什么?
TypeScript是一种给JavaScript添加特性的拓展语言,支持es5和es6,是JavaScript的超集。增加的功能主要有类型批注、类型擦除、接口、枚举、Mixin、泛型编程、名字空间、元祖、await等等。
TypeScript的基础语法
TypeScript程序由一下几部分组成。
基础类型
- 布尔类型
let isDone: boolean = false; - 数字类型
let num: number = 2; - 字符串类型
let str: string = 'hello' - 数组
- 第一种方式
let ary: number[] = [1,3,5] - 第二种方式
let ary: Array<number> = [1,3,56]
- 第一种方式
- 元祖 Tuple
let x: [string,number] x = ['hello',3] console.log(x[0].substr(0))//'hello' - 枚举
enum color {red,green,blue}
let c: color = color.green
console.log(c) //1 //默认情况下从0开始编号。我们也可以手动进行赋值;例如
// 从1开始编号
enum color {red = 1, green, blue}
//或者全部手动赋值
enum color {red = 2,green = 5,blue = 6}
let colorName: string = color[5]
console.log(colorName)// green
模块
函数
变量
语句和表达式
注释
编译TypeScript
- 在npm中输入tsc将ts文件编译,一旦编译成功会在相同的目录下生成一个js文件。
接口
- 接口用来作为一个类型的批注。实例如下
interface Shape {
name:string;
width:nubmer;
height:nubmer;
color?:string;
//其中传参时,这里的color可有可无,如果没有color则为undefined;如果name、width、height、其中缺一个编译时就会报错
}
function geeter (shape: Shape){
let total = shape.width + shape.height;
return "我是"+ shape.name + "在" + total +"cm的盒子里"+“颜色是”+"shape.color";
}
console.log(geeter({name:'王雪',width:12,height:34,color:"red"}))
//编译以后输出 我是王雪在46cm的盒子里颜色是red
类
- 先上实例
class Shape {
area:number;
private color:string;
constructor(public name:string,width:number,height:number){
//如果constructor里的参数不加public,那它的作用域是局部作用域,在shout方法中不能使用,否则代码编译会报错。
加上public,意味着里面的参数是类里的全局作用域,他可以在任何地方使用。
this.area = width + height;
this.color = 'pink';
}
shout(){
return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
}
}
let sh = new Shape('小雪', 2, 4)
console.log(sh.shout())//I'm pink 小雪 with an area of 6 cm squared.
类的继承
class Son extends Shape {
leng:number;
constructor(public name:string, width:number, height:number, length:number){
super(name,width,height)
this.leng = this.area* length
}
shout(){
return "I'm " + this.name + " with a volume of " + this.leng + " cm cube.";
};
superShout(){
return super.shout();
}
}
let son = new Son('son', 1, 2, 3)
console.log(son.shout());//I'm son with a volume of 9 cm cube.
console.log(son.superShout());//'m pink son with an area of 3 cm squared.