export class ConstructorExample { execute() { //类静态部分与实例部分 //先定义静态部分的接口 interface ClockInterface { tick(); } interface ClockConstructor { new(hour: number, minute: number): ClockInterface; show(): void; } // class Clock implements ClockInterface { // constructor(hour: number, minute: number) { // } // tick() { // } // } let Clock: ClockConstructor; let clock = new Clock(1, 1); Clock.show(); interface Map2 { forEach(callback: (key: K, value: V, map: Map2) => void): void; } interface MapConstructor2 { new (): Map2; } class Map3 implements Map2 { forEach(callback: (key: K, value: V, map?: Map2) => void): void { } } class Char { mp: number; hp: number; } let map = new Map3(); map.forEach((key, value, map) => { }); //----------------------------接口与类的区别------------------------------// //1、什么时候用接口? //2、什么时候用类? //当很多时候我们需要毫无关系的对象集提供统一的属性或者方法调用,此用用接口更好,例如: interface WeightInfo { weight: number; } interface ColorInfo { color: number; } class Man implements WeightInfo { weight: number; } class Car implements WeightInfo, ColorInfo { weight: number; color: number; } class Wall implements ColorInfo { color: number; } function choose(object: WeightInfo | ColorInfo) { } class A_ { hp: number; mp: number; } class B_ extends A_ { o: number } class C_ { } let target = {}; Object.assign(target, new A_()); interface Bird { fly(): void; layEggs(): void; } interface Fish { swim(): void; layEggs(): void; } //写起来十分繁琐 let animal: Bird | Fish; if ((animal).swim) { (animal).swim(); } else { (animal).fly(); } /** -------------类型谓词------------------ */ //简化写法 function isFish(pet: Bird | Fish): pet is Fish { return (pet).swim !== undefined; } if (isFish(animal)) { animal.swim(); } else { animal.fly(); } } }