I have the following, which is currently producing a type error. Typescript error: Property 'code' does not exist on type 'KeyboardEvent'
const onKeyDownSim = (event: React.KeyboardEvent<HTMLInputElement>) => {
const element = event.target as HTMLElement;
if (event.code === 'Space') element.click();
};
looking at the definition for the KeyboardEvent in React, I understand why it's complaining as the 'code' property doesn't exist here. It does however have all the old methods for doing the same thing. deprecated charCode etc. Any ideas how to work around this?
interface KeyboardEvent<T = Element> extends SyntheticEvent<T, NativeKeyboardEvent> {
altKey: boolean;
/** @deprecated */
charCode: number;
ctrlKey: boolean;
/**
* See [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#keys-modifier). for a list of valid (case-sensitive) arguments to this method.
*/
getModifierState(key: string): boolean;
/**
* See the [DOM Level 3 Events spec](https://www.w3.org/TR/uievents-key/#named-key-attribute-values). for possible values
*/
key: string;
/** @deprecated */
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
/** @deprecated */
which: number;
}
CodePudding user response:
You can use the key
property to determine what character corresponds with the key event: the value for space will be " "
for modern browser ("Spacebar"
for older ones).
Note that according to the Changelog the code
property has been added to React.KeyboardEvent
in React v17, so upgrading your React version should allow you to use code
.
Also note that, as you might know, code
and key
are not exactly the same: code
represents the physical key on the keyboard, while key
represents the generated character.