1. 数字、布尔、字符串
let num: number = 6;let str: string = "6";let bool: boolean = false;
2. 数组
// Arraylet numArr1: number[] = [4, 3, 9, 9];// 也能够利用泛型let numArr2: Array<number> = [7, 1, 3, 5];
3. 元组
元组能够进一步标准固定地位的类型,且长度不可变;
// tupplelet person1: [number, string] = [17, "aYao"]
4. Union 类型
// Unionlet uni: string | number;uni = 2;uni = "2";
5. Enum 枚举
// Enumenum Color { red, green, blue}let color = Color.blueconsole.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]); // stringconst l2 = lastInArr(["1", "2", "3", "4"]); // number// 指定类型const l3 = lastInArr<string | number>(["1", "2", "3", "4"]); // number | string