Open dimitropoulos opened 4 years ago
This will help prevent scenarios like:
if (event.key === "ArowDown") { // <- "ArrowDown" is misspelled here
Unfortunately as soon as you have string
in
readonly key: string | ModifierKeys | WhitespaceKeys ...
ArowDown
is valid value and so no error will be reported.
As for suggestions see #29729
We could go the route of ‘csstypes’ and have it be an external package that augments the current type definitions, though I’m not sure it will work if the type is already the wider string
huh. I knew that ArowDown
would be a valid value but was hoping that the UX improvement of the autocomplete would be a big enough win to make this all worth it.
I was under the impression that the autocomplete would continue to work, and didn't realize that string |
would clobber it... hmph.
With (works well):
Without (doesn't work):
The LiteralUnion
type was created in type-fest for this purpose. Maybe it can be used while #29729 is not solved.
For whatever it's worth I can confirm that LiteralUnion
works in this use-case (notice that ''
is not an error, whereas before it was an error; also notice that the autocomplete works).
I'm open @ferdaber's suggestion of making an external definition, like dom-keyboardevent-key-types.d.ts
or something. If there's consensus from others (@IllusionMH), then I can move forward with making that package. It'd be nice if it lived under this repo (in the same directory as lib.dom.d.ts
), but I can live with either. We can, therefore, much more easily use LiteralUnion
from type-fest
.
I think this is blocked on #29729 getting solved but could proceed after that
The IntelliSense will help prevent many scenarios. Even without LiteralUnion.
I created a small external package that contains the types of the KeyboardEvent.key while the current-suggestion is blocked.
Search Terms
keyCode
KeyboardEvent
KeyboardEvent.key
KeyboardEvent.keyCode
Suggestion
Include
KeyboardEvent.key
values in theKeyboardEvent
interface.The current implementation is:
See here for a list of some possible values.
Here is my suggestion for how this type can be usefully updated:
In the above I left out
EditingKeys
,UIKeys
,DeviceKeys
,IMEKeys
,PhoneKeys
,MultimediaKeys
,AudioControlKeys
,TVControlKeys
,MediaControllerKeys
,SpeechRecognitionKeys
,DocumentKeys
,ApplicationSelectorKeys
, andBrowserControlKeys
, but we could either include them all at the start or just as necessary.Use Cases
When a user is accessing the
KeyboardEvent.key
API, a sane set of the known defaults should be available for type checking.Examples
This will help prevent scenarios like:
Since users will get completion on common values when typing.
Checklist
My suggestion meets these guidelines: