作为JavaScript的升级版,能解决JavaScript弱类型的弱点,建议使用。
特点:各种type,各种提示啊。
效果:
如何使用
// 安装
npm install -g typescript
npm install -g ts-node
// 直接运行
ts-node filename.ts
// 转换为js文件,使用idea时,也可以通过设置自动编译成为js
tsc filename.ts
变量定义
// 普通变量
let strTmp: string = "123";
let isDone: boolean = false;
// 数组
let listAny: Array<any> = [1, 2, 3, "4"];
let listNumber: Array<number> = [1, 2, 3];
// 枚举
enum Color {Red, Green, Blue};
Color.Green; // 1
Color[1]; // Green
函数
let add = function (left: number, right: number): number {
return left + right;
};
console.log(add(1, 2));
类
// 类:封装方法和数据--------------
class Shape {
name: string;
area: number;
color: string;
constructor(name: string, width: number, height: number) {
this.area = width * height;
this.color = "pink";
};
shoutout() {
return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
}
}
let square = new Shape("square", 30, 30);
console.log(square.shoutout());
// 类的继承------------------
class Shape3D extends Shape {
volume: number;
constructor(public name: string, width: number, height: number, length: number) {
super(name, width, height);
this.volume = length * this.area;
};
shoutout() {
return "I'm " + this.name + " with a volume of " + this.volume + " cm cube.";
}
superShout() {
return super.shoutout();
}
}
var cube = new Shape3D("cube", 30, 30, 30);
console.log(cube.shoutout());
console.log(cube.superShout());
// 箭头函数:可以自动修改this指向,settimeout里面的this默认为windows------------
class Shape1 {
name: string = "rectangle";
popup() {
console.log('This inside popup(): ' + this.name);
setTimeout(() => {
console.log('This inside setTimeout(): ' + this.name);
console.log("I'm a " + this.name + "!");
}, 1);
}
};
new Shape1().popup();
这短短的一生我们最终都会失去,不放大胆一点,爱一个人、攀一座山、追一个梦!