Skip to content

A TypeScript string enum for compile-time safety when working with event.key

License

Notifications You must be signed in to change notification settings

GabiGrin/ts-key-enum

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ts-key-enum

A TypeScript string enum for compile-time safety when working with event.key.

Install

npm install ts-key-enum --save

Purpose

Tired of referencing keyboard keys with a string?

onKeyPress = (ev) => {

    // whoops, spelled "Enter" wrong!
    if (ev.key === 'ENter') {
        ...
    }
}

Me too. With this module, you can do this instead (in a TypeScript file):

onKeyPress = (ev) => {

    // much better
    if (ev.key === Key.Enter) {
        ...
    }
}

Background

This is similar to the ts-keycode-enum module, but it provides an enum with string values that correspond with the event.key values instead of number values that correspond to the deprecated event.which and event.keyCode values.

Usage

To use this module, import the Key enum at the top of your TypeScript file:

import { Key } from 'ts-key-enum';

You can now use the enum value in place of key strings throughout the file:

// if (ev.key === 'Escape') { ... }
if (ev.key === Key.Escape) { ... }

See Key.enum.ts for a complete list of available keys.

In addition, to aid with readability, a number of enum values have aliases. For example:

// this is true - these values are equal
Key.Hash === Key.Pound

Use whichever value makes more sense for readability.

Building

To build this module yourself, first install its dependencies using

npm install

Then, run the build using

npm run build

Build output is placed in the dist directory.

Contributions

This module only contains some of the most commonly-used key string values. There are many more, as you can see by taking a look at this complete list. If this module is missing enum values that you need, feel free to request the additions via an issue or a pull request.

License

MIT

About

A TypeScript string enum for compile-time safety when working with event.key

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 86.5%
  • Shell 13.5%