完整教程:https://ts.xcatliu.com/

作为JavaScript的升级版,能解决JavaScript弱类型的弱点,建议使用。
特点:各种type,各种提示啊。

效果:

image.png

如何使用

  1. // 安装
  2. npm install -g typescript
  3. npm install -g ts-node
  4. // 直接运行
  5. ts-node filename.ts
  6. // 转换为js文件,使用idea时,也可以通过设置自动编译成为js
  7. tsc filename.ts

变量定义

  1. // 普通变量
  2. let strTmp: string = "123";
  3. let isDone: boolean = false;
  4. // 数组
  5. let listAny: Array<any> = [1, 2, 3, "4"];
  6. let listNumber: Array<number> = [1, 2, 3];
  7. // 枚举
  8. enum Color {Red, Green, Blue};
  9. Color.Green; // 1
  10. Color[1]; // Green

函数

  1. let add = function (left: number, right: number): number {
  2. return left + right;
  3. };
  4. console.log(add(1, 2));

  1. // 类:封装方法和数据--------------
  2. class Shape {
  3. name: string;
  4. area: number;
  5. color: string;
  6. constructor(name: string, width: number, height: number) {
  7. this.area = width * height;
  8. this.color = "pink";
  9. };
  10. shoutout() {
  11. return "I'm " + this.color + " " + this.name + " with an area of " + this.area + " cm squared.";
  12. }
  13. }
  14. let square = new Shape("square", 30, 30);
  15. console.log(square.shoutout());
  16. // 类的继承------------------
  17. class Shape3D extends Shape {
  18. volume: number;
  19. constructor(public name: string, width: number, height: number, length: number) {
  20. super(name, width, height);
  21. this.volume = length * this.area;
  22. };
  23. shoutout() {
  24. return "I'm " + this.name + " with a volume of " + this.volume + " cm cube.";
  25. }
  26. superShout() {
  27. return super.shoutout();
  28. }
  29. }
  30. var cube = new Shape3D("cube", 30, 30, 30);
  31. console.log(cube.shoutout());
  32. console.log(cube.superShout());
  33. // 箭头函数:可以自动修改this指向,settimeout里面的this默认为windows------------
  34. class Shape1 {
  35. name: string = "rectangle";
  36. popup() {
  37. console.log('This inside popup(): ' + this.name);
  38. setTimeout(() => {
  39. console.log('This inside setTimeout(): ' + this.name);
  40. console.log("I'm a " + this.name + "!");
  41. }, 1);
  42. }
  43. };
  44. new Shape1().popup();

这短短的一生我们最终都会失去,不放大胆一点,爱一个人、攀一座山、追一个梦!