TypeScript: Get the Unicode value of the pressed key

Updated: February 14, 2024 By: Guest Contributor Post a comment

Overview

Handling keyboard inputs effectively is a crucial aspect of creating responsive web applications. TypeScript, a superset of JavaScript, offers more robust solutions in achieving this with its strong typing and compilation features. In this tutorial, we’ll explore how to capture and use the Unicode values of pressed keys in TypeScript. Understanding Unicode value capturing can be incredibly beneficial for various applications, such as creating keyboard shortcuts, handling international character input, and designing accessible web applications.

Firstly, let’s understand what Unicode is. Unicode is a universal encoding standard for characters, ensuring that every character across different languages and scripts is represented using a unique number, known as a Unicode point. By capturing the Unicode value of a pressed key, developers can perform specific actions based on the input, irrespective of the keyboard layout or language.

Setting Up Your TypeScript Environment

Before diving into code examples, ensure you have a TypeScript environment set up. If you’re new to TypeScript, you can start by installing it globally via npm:

npm install -g typescript

Next, initialize a new project:

tsc --init

This command creates a tsconfig.json file, which is essential for configuring your TypeScript project settings.

Capturing Key Events

In order to obtain the Unicode value of a pressed key, we must first capture the key event. This can be done using the keydown or keypress events in TypeScript.

Let’s start with a simple example where we add an event listener to the whole document:

document.addEventListener('keydown', (event: KeyboardEvent) => {
  console.log(event.key, event.keyCode, event.code);
});

This snippet listens for a keydown event and logs the key pressed, its keyCode (deprecated), and its code (more reliable, represents the physical key on the keyboard).

However, to get the Unicode value, we focus on the event.key value, which represents the character or characters generated by that key or combination of keys.

Extracting Unicode Values

Now, let’s write a function to extract the Unicode value from the event.key:

function getUnicodeValue(key: string): number {
  return key.charCodeAt(0);
}

Our getUnicodeValue function takes a string key, which is the value of event.key, and returns its Unicode value using the charCodeAt(0) method, which provides the Unicode of the character at position 0 in the string.

To apply this function within our event listener:

document.addEventListener('keydown', (event: KeyboardEvent) => {
  console.log(`The unicode value of ${event.key} is ${getUnicodeValue(event.key)}`);
});

This will log the Unicode value of any key pressed while focusing on any part of the document. This approach is particularly useful for global keyboard event handling.

Handling Special Keys and Combinations

It’s important to note that not all keys generate characters (e.g., CTRL, ALT, SHIFT). For these non-character keys, event.key will not hold a character value, and attempting to obtain its Unicode value might not be meaningful or will return an unexpected result. For such cases, you might want to exclude these keys from triggering your Unicode extraction function:

document.addEventListener('keydown', (event: KeyboardEvent) => {
  if (!event.key.match(/Control|Shift|Alt|Meta/)) {
    console.log(`The unicode value of ${event.key} is ${getUnicodeValue(event.key)}`);
  }
});

This code snippet excludes the Control, Shift, Alt, and Meta keys from logging their Unicode values.

Real-World Application: Handling International Input

Capturing the Unicode value of keys can be crucial for international applications requiring support for multiple languages. By leveraging Unicode values, you can ensure that your application accurately processes and displays characters from various languages and scripts. Here’s an example:

function handleInternationalInput(event: KeyboardEvent): void {
  const unicodeValue = getUnicodeValue(event.key);
  // Assume a function that determines if the Unicode value is a valid character in your application's supported languages
  if (isValidCharacter(unicodeValue)) {
    // Handle the character input
  }
}

In this way, by focusing on Unicode values, developers can create more inclusive and universally functional web applications.

Conclusion

In summary, capturing and utilizing the Unicode value of pressed keys in TypeScript is a powerful approach for handling keyboard input. Whether for processing international input, creating keyboard shortcuts, or enhancing user accessibility, understanding and implementing Unicode value extraction can greatly benefit your projects. As developers continue to design global and accessible applications, proficiency in such techniques will be increasingly valuable.