Typescript keyboard event : argument of type 'Event' is not assignable to parameter of type 'KeyboardEvent'
TypeScript isn't able to make the full leap here, because all it knows is the event name will be a string, so the most general event type is used.
Examples below converted to a stand alone running example - so I've taken things "out of a class" for the demo...
While the strings are keydown
and keyup
you can guarantee the type safety, and overrule the compiler:
let listenTo = (window: Window) => {
['keydown', 'keyup'].forEach(eventName => {
window.addEventListener(eventName, e => {
handleEvent(<any>e);
});
});
}
let handleEvent = (event: KeyboardEvent) => {
const { key } = event;
//...
}
This would fall down if some other string was added to your array of event names.
Full type safety is available when using a string directly, due to specialized signatures:
window.addEventListener('keydown', e => {
handleEvent(e); // e is KeyboardEvent
});
So you could type your array more strongly to get the correct types goodness:
type KeyboardEventNames = 'keydown' | 'keyup';
let listenTo = (window: Window) => {
const eventNames: KeyboardEventNames[] = ['keydown', 'keyup'];
eventNames.forEach(eventName => {
window.addEventListener(eventName, e => {
handleEvent(e);
});
});
}
let handleEvent = (event: KeyboardEvent) => {
const { key } = event;
//...
}
In this last example, we restict the type of elements in the array to only keyboard event names, so the compiler now knows it isn't dealing with just any old string, and can infer the event type.