【发布时间】:2021-09-16 00:53:16
【问题描述】:
我正在尝试将以下代码用于事件调度程序,并更加指定使用的类型(类和接口)。
- 请注意,我通常有兴趣了解为什么我在此处使用类型/类/接口/泛型类型不起作用,并且对事件本身不太感兴趣。
type Handler<E> = (event: E) => void;
class EventDispatcher<E> {
private handlers: Handler<E>[] = [];
fire(event: E) {
for (let h of this.handlers)
h(event);
}
register(handler: Handler<E>) {
this.handlers.push(handler);
}
}
我想要达到的目标:
-
使用 Typescript 的
CustomEvent<any>而不是E。 -
能够定义
extendsCustomEvent<any>的具体自定义事件,例如:export class FormClearedEvent extends CustomEvent<any> { constructor() { super("formCleared"); } } -
导出那些特定的自定义事件,连同处理程序和事件分派器
第一次尝试,未编译:
export type Handler<CustomEvent<any>> = (event: CustomEvent<any>) => void; // <-- doesn't compile
// Also, using CustomEvent<any> as the type parameter for the dispacther and its methods, doesn't compile as well.
第二次尝试,让我到处重复SpecificEvent extends CustomEvent<any>>,并且无法编译:
export type Handler<SpecificEvent extends CustomEvent<any>> = (event: SpecificEvent) => void;
export class EventDispatcher<SpecificEvent extends CustomEvent<any>> {
private handlers: Handler<SpecificEvent extends CustomEvent<any>>[] = []; // <-- doesn't compile
fire(event: SpecificEvent extends CustomEvent<any>) { // <-- doesn't compile
for (let handler of this.handlers) {
handler(event);
}
}
register(handler: Handler<SpecificEvent extends CustomEvent<any>>) { // <-- doesn't compile
this.handlers.push(handler);
}
}
// specific events
export class FormClearedEvent extends CustomEvent<any> {
constructor() {
super("formCleared");
}
}
第三次尝试,成功了,但现在我有两个真正相同的课程(CustomEvent<any> 和 SpecificEvent):
// specific events
class SpecificEvent extends CustomEvent<any> { }
export class FormClearedEvent extends CustomEvent<any> {
constructor() {
super("formCleared");
}
}
// SpecificEvent handler
export type Handler<SpecificEvent> = (event: SpecificEvent) => void;
// SpecificEvent dispatcher
export class EventDispatcher<SpecificEvent> {
private handlers: Handler<SpecificEvent>[] = [];
fire(event: SpecificEvent) {
for (let handler of this.handlers) {
handler(event);
}
}
register(handler: Handler<SpecificEvent>) {
this.handlers.push(handler);
}
}
我的问题:
- 为什么我的第一次尝试没有编译?
- 为什么我第二次尝试的某些代码无法编译?
- 我能比第三种方法做得更好吗?
【问题讨论】:
标签: typescript class types interface typescript-generics