我正在阅读https://www.typescriptlang.org/docs/handbook/type-compatibility.html中的一个示例:
enum EventType { Mouse, Keyboard }
interface Event { timestamp: number; }
interface MouseEvent extends Event { x: number; y: number }
interface KeyEvent extends Event { keyCode: number }
function listenEvent(eventType: EventType, handler: (n: Event) => void) {
/* ... */
}
// Unsound, but useful and common
listenEvent(EventType.Mouse, (e: MouseEvent) => console.log(e.x + "," + e.y));
// Undesirable alternatives in presence of soundness
listenEvent(EventType.Mouse, (e: Event) => console.log((<MouseEvent>e).x + "," + (<MouseEvent>e).y));
listenEvent(EventType.Mouse, <(e: Event) => void>((e: MouseEvent) => console.log(e.x + "," + e.y)));
// Still disallowed (clear error). Type safety enforced for wholly incompatible types
listenEvent(EventType.Mouse, (e: number) => console.log(e));
此示例说明了javascript的常见用法。
我的问题是,如果我启用标志strictFunctionTypes
,应如何实现此示例?请注意,标记打开时,提示错误Argument of type '(e: MouseEvent) => void' is not assignable to parameter of type '(n: Event | MouseEvent) => void'
。