我不明白为什么这会给我一个错误(使用编译器选项"strict": true
)。
class EventX {
public type: string
constructor(type: string) {
this.type = type
}
}
class ClickEvent extends EventX {
public x: number
constructor(type: string, x: number) {
super(type);
this.x = x;
}
}
interface Events {
[eventType: string]: (event: EventX) => any
click: (e: ClickEvent) => any // TS2411: Property 'click' of type '(e: ClickEvent) => any' is not assignable to string index type '(event: EventX) => any'.
}
顺便说一下,这很好
interface Events {
[eventType: string]: EventX
click: ClickEvent
}
所以我认为这是(event: EventX) => any
造成问题的原因。但是,这怎么了?我该如何解决?
问题在于索引签名必须包含值可能具有的所有可能的类型:
interface Events {
click: (event: ClickEvent) => any;
[eventType: string]: ((event: EventX) => any) | ((event: ClickEvent) => any);
}
这是由于所有键都包含在索引签名中[x: string]
,因此检查了所有键的一致性-并且由于(event:ClickEvent)=> any不能分配给(event:EventX)=> any,因此会引发错误
编辑:ZoltánMihályi有一个更好的解释。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句