关于前端:Typescript-学习笔记

1次阅读

共计 1277 个字符,预计需要花费 4 分钟才能阅读完成。

1. 数字、布尔、字符串

let num: number = 6;
let str: string = "6";
let bool: boolean = false;

2. 数组

// Array
let numArr1: number[] = [4, 3, 9, 9];
// 也能够利用泛型
let numArr2: Array<number> = [7, 1, 3, 5];

3. 元组

元组能够进一步标准固定地位的类型,且长度不可变;

// tupple
let person1: [number, string] = [17, "aYao"]

4. Union 类型

// Union
let uni: string | number;
uni = 2;
uni = "2";

5. Enum 枚举

// Enum
enum Color {
  red,
  green,
  blue
}
let color = Color.blue
console.log(color) // 2

6. any

let randomVal: any = 666;
randomVal = "777";
randomVal = {};

7. void、undefined 和 never

function printResult(): void {console.log("lalala~");
}

console.log(printResult()) // undefined

8. interface 与 class

interface IPoint {
  x: number;
  y: number;
  drawPoint: () => void;
  getDistances: (p: IPoint) => number;
}
// let drawPoint = (point: Point) => {//   console.log({ x: point.x, y: point.y});
// };
// drawPoint({x: 4, y: 7});
class Point implements IPoint {
  x: number;
  y: number;
  // 构造函数 constructor;?: 示意可选参数,能够不给其赋值
  constructor(x?: number, y?: number) {
    this.x = x;
    this.y = y;
  }

  drawPoint = () => {console.log("x:" + this.x + ",y:" + this.y);
  };
  getDistances = (p: IPoint) => {return Math.pow(p.x - this.x, 2) + Math.pow(p.y - this.y, 2);
  };
}

const point = new Point(2, 3); 
point.drawPoint(); // x:2,y:3

9. Generics

// 传入什么类型就返回什么类型
let lastInArr = <T>(arr: Array<T>) => {return arr[arr.length - 1];
};
const l1 = lastInArr([1, 2, 3, 4]); // string
const l2 = lastInArr(["1", "2", "3", "4"]); // number
// 指定类型
const l3 = lastInArr<string | number>(["1", "2", "3", "4"]); // number | string
正文完
 0