我正在查看打字稿的文档并找到了一个例子
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
interface ClockInterface {
tick();
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}
class DigitalClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("beep beep");
}
}
class AnalogClock implements ClockInterface {
constructor(h: number, m: number) { }
tick() {
console.log("tick tock");
}
}
let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
我掌握了界面的所有概念,但我坚持在匿名对象声明的界面中使用 new 关键字的概念
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}
我无法了解它背后的目的是什么以及它是如何工作的?我在https://www.typescriptlang.org/docs/handbook/interfaces.html
上找到了它有人可以帮帮我吗?
答案 0 :(得分:3)
它声明此接口的对象是构造函数,并使用new
关键字进行调用。