prefer-keyboardevent-key-over-keycode-javascript
Replace deprecated KeyboardEvent.keyCode checks with standards-based event.key string comparisons in JavaScript and TypeScript keyboard handlers.
What It Rewrites
- Equality and inequality checks against mapped numeric key codes:
===,!==,==,!= - Comparisons against file-local
constaliases that resolve to mapped numeric key codes - Reversed comparisons such as
13 === e.keyCode - Bracket access such as
e['keyCode'] === 9 - Boolean compositions that contain safe
keyCodecomparisons switch (event.keyCode)when every non-defaultcaselabel is a mapped numeric literal
Default key mapping:
8 -> 'Backspace'9 -> 'Tab'13 -> 'Enter'27 -> 'Escape'32 -> ' '37 -> 'ArrowLeft'38 -> 'ArrowUp'39 -> 'ArrowRight'40 -> 'ArrowDown'46 -> 'Delete'
Handler Heuristics
By default, the codemod only rewrites keyCode usage when it appears in keyboard-oriented contexts:
- DOM listeners passed to
addEventListener('keydown' | 'keyup' | 'keypress', ...) - JSX handlers such as
onKeyDown,onKeyUp, andonKeyPress - Functions whose matching event parameter is explicitly typed as
KeyboardEventorReact.KeyboardEvent - Keyboard-named handlers such as
handleKeyDown
This keeps the transform conservative for user-defined .keyCode properties outside browser keyboard handling.
Exclusions
- Assignments and updates such as
e.keyCode = 13ore.keyCode++ - Unmapped numeric key codes
- Comparisons against non-literal values that cannot be folded to a mapped numeric key code
- Branches that already mix the same object's
keyCodeandkeychecks - TypeScript handlers whose event parameter is explicitly typed as a non-keyboard event, unless
unsafe=true switchstatements with any non-default case label that cannot be mapped deterministically
Parameters
force=true: bypass keyboard-context heuristics and rewrite any safekeyCodecomparison or switchunsafe=true: allow rewrites even when the matching TypeScript event parameter is explicitly typed as a non-keyboard event
Before And After
js
js
Usage
bash
Development
bash
License
MIT