【发布时间】:2018-08-30 12:36:00
【问题描述】:
在 TypeScript 中,我有一个扩展模块 Events 的类,它的声明中包含以下内容:
on(event: string | symbol, listener: (...args: any[]) => void): this;
扩展模块的类会为侦听器发出许多具有不同签名的事件。我可以为此属性创建多个覆盖,这些覆盖稍微更具体,但仍与签名匹配。比如:
export class Agent extends Events {
constructor(conf: IAgentConf);
on(event: 'eventA', listener: (body: IAEvent) => void): this
on(event: 'eventB', listener: (body: IPayload<IBEvent>) => void):this;
on(event: 'eventC', listener: (body: ICEvent[]) => void): this;
...
}
使用这种类型,TypeScript 可以在声明事件侦听器时识别回调的形状。
但是,当我进一步扩展这个对象时,我遇到了问题,新对象发出一个新事件:
class MyAgent extends Agent {
static EventD: string = 'EventD';
init: () => void;
on(event: 'EventD', listener: (body: IEventD) => void):this;
constructor(conf: IAgentConf) {
super(conf);
this.init = () => {
this.on('EventA', body => {
this.emit(MyAgent.EventD, body.thingy);
});
};
init();
}
}
不幸的是,这不起作用。我得到了错误:
(TS) Property 'on' in type 'MyAgent' is not assignable to the same property in base type 'Agent'.
是否可以进一步覆盖孙子类中祖父类的属性?
【问题讨论】:
标签: typescript overriding