Typescript 学习笔记

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 = [7, 1, 3, 5];

3. 元组
【Typescript 学习笔记】元组可以进一步规范固定位置的类型,且长度不可变;
// 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 = (arr: Array) => { return arr[arr.length - 1]; }; const l1 = lastInArr([1, 2, 3, 4]); // string const l2 = lastInArr(["1", "2", "3", "4"]); // number // 指定类型 const l3 = lastInArr(["1", "2", "3", "4"]); // number | string

    推荐阅读