Home > Blockchain >  e.charcode in TypeScript
e.charcode in TypeScript

Time:02-01

I dont undertand why this does not work

const addRate = (e: { charCode: KeyboardEvent }) => {
 if (e.charCode >= 48) {
      ...
 }
}

I get this:

'Operator '>=' cannot be applied to types 'KeyboardEvent' and 'number'.ts(2365)'

But e.charcode is indeed a KeyboardEvent and this works somewhere else on my app

const addString = (e: { target: HTMLInputElement }) => ....

CodePudding user response:

There are two problems:

  1. It's charCode, not charcode.

  2. You've applied the parameter type incorrectly, it should be:

    const addRate = ({ charCode }: KeyboardEvent) => {
    

    You need to apply the event type to the entire parameter you're destructuring.

Note that charCode is deprecated (though it'll never actually go away), new code should use code and/or key (depending on the event).


In the comments, you've asked how you'd "do this" with a change handler. But the change event isn't a KeyboardEvent, it's just an Event (actually, React's types define a ChangeEvent for it, presumably so type is the string literal type "change" rather than a string). Then you said you wanted to handle both.

You can do that by specifying that the event is either Event (or, in React, a ChangeEvent) or KeyboardEvent, and then branching based on whether it's a keyboard event:

import React, { ChangeEvent, KeyboardEvent } from "react";

function Example() {
    const addRate = (e: ChangeEvent | KeyboardEvent) => {
        // ...code that doesn't care which event it is...
        if ("key" in e) {
            // Here, TypeScript will kow that `e` is a `KeyboardEvent`
            // ...code that needs to know the `code` or `key`...
        }
    };

    return <input type="text" onChange={addRate} onKeyDown={addRate} />;
}

Playground link

  •  Tags:  
  • Related