Home > OS >  Property 'data' does not exist on type 'Event'. ts(2339)
Property 'data' does not exist on type 'Event'. ts(2339)

Time:10-30

I have an HTML textarea and when the user types on it, I need to print the character that the user inputs to the console.

So I tried the following code

HTML (index.html):

<textarea id="editor"></textarea>

TypeScript (script.ts):

const editor = document.getElementById("editor") as HTMLTextAreaElement;

editor.addEventListener("input", e => {
    console.log(e.data);
});

This works well as I expected but when compiling this TypeScript code to JavaScript, the compiler gives the following error:

script.ts:4:19 - error TS2339: Property 'data' does not exist on type 'Event'.

4     console.log(e.data);
                    ~~~~


Found 1 error in script.ts:4

How do I fix this?

CodePudding user response:

You could check if your event e is an instance of InputEvent as InputEvents have a data property.

editor.addEventListener("input", e => {
  if (e instanceof InputEvent)
    console.log(e.data);
});

Or you can return early:

editor.addEventListener("input", e => {
  if (!(e instanceof InputEvent))
    return;

  console.log(e.data);
  // ...
});

CodePudding user response:

You need to tell typescript, that the event is not a generic event, but an input event (because only input events have the property data)

So something like this would work:

const x = function (event: InputEvent) {console.log(event.data)}
document.getElementById("test")?.addEventListener("input", x)

You could probably also achieve that in one line (without the need to decleare x) with the use of Generics and such (but since I'm not yet proficient with them I don't really know how)

  • Related