gpt4 book ai didi

typescript - 接口(interface)中关键字 "new"是什么意思?

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:53 24 4
gpt4 key购买 nike

我正在浏览 typescript 的文档并找到一个例子

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);

我了解了接口(interface)的所有概念,但我仍然坚持在匿名对象声明接口(interface)中使用关键字的概念

 interface ClockConstructor {
new (hour: number, minute: number): ClockInterface;
}

我不明白它背后的目的是什么以及它是如何工作的?我在 https://www.typescriptlang.org/docs/handbook/interfaces.html 上找到了它

有人可以帮我解决这个问题吗?

最佳答案

它声明此接口(interface)的对象是构造函数,并且可以使用new 关键字调用。

关于typescript - 接口(interface)中关键字 "new"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45462476/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com