typescript 快速入门2

markdown ### 构造函数 ```text # 个人认为非必要情况下不要使用构造函数声明属性 class huamn{ constructor(public name: string,public age: number) { this.name = name this.age = age } get getName() { return this.name } say() { console.log('say') } } console.log(new huamn('zhangsan', 18).getName); ``` ### 抽象类 ```text abstract class Geom { getType() { return 'Gemo'; } abstract getArea(): number; } class Circle extends Geom { getArea() { return 123; } } console.log(new Circle().getType()); ``` ### 联合类型 ```text interface Bird { fly: boolean; sing: () => {}; } interface Dog { fly: boolean; bark: () => {}; } // 类型断言 function trainAnimal(animal: Bird | Dog) { if (animal.fly) { (animal as Bird).sing(); } else { (animal as Dog).bark(); } } // in 语法 function trainAnimalSecond(animal: Bird | Dog) { if ('sing' in animal) { animal.sing(); } else { animal.bark(); } } // typeof 语法 function add(first: string | number, second: string | number) { if (typeof first === 'string' || typeof second === 'string') { return `${first}${second}`; } return first + second; } // instanceof 语法 class NumberObj { count: number; } function addObj(first: object | NumberObj, second: object | NumberObj) { if (first instanceof NumberObj && second instanceof NumberObj) { return first.count + second.count; } return 0; } ``` ### 枚举 ```text // 数字枚举 enum Status { OFFLINE, ONLINE, DOTKONWSTATUS, } // 字符串枚举 enum Message { MASSAGE = 'massage', SPA = 'spa', DABAOJIAN = 'dabaojian', } // 常量枚举 const enum Month { Jan, Feb, Mar, } ``` ### 泛型 ```text // 泛型 function join(first: T, second: T) { return `${first}${second}`; } join('1', 1); // 泛型中数组的使用 function myFun(params: T[]) { return params; } myFun(['1', '2']); // 泛型中类的使用 ```

评论