The object 'key' is not a valid property of the type 'Event'

Recently, I decided to delve into Tauri using vanilla Typescript code.

Oddly enough, when working in vscode, it flagged event.key and foo_input.value as not properties of Event. However, when running the Tauri application, everything worked perfectly fine.

const foo_input = document.querySelector(".foo");

foo_input?.addEventListener("keydown", event => {
    if (event.key !== 'Enter') return;

    console.log(foo_input.value);
});
Property 'key' does not exist on type 'Event'.ts(2339)

Property 'value' does not exist on type 'Element'.ts(2339)

Here is the element with the .foo class:

<body>
  <main>
    ...
    <input type="text" class="foo" placeholder="Lorem ipsum dolor sit amet">
    ...
  </main>
</body>

Realizing that I was actually utilizing KeyboardEvent, I attempted to specify the event.

const foo_input: Element | null = document.querySelector(".foo");

foo_input?.addEventListener("keydown", (event: KeyboardEvent) => {
    if (event.key !== 'Enter') return;

    console.log(foo_input.value);
});

This attempt resulted in another error message:


  Overload 1 of 2, '(type: keyof ElementEventMap, listener: (this: Element, ev: Event) => any, options?: boolean | AddEventListenerOptions | undefined): void | undefined', gave the following error.
    Argument of type '"keydown"' is not assignable to parameter of type 'keyof ElementEventMap'.
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void | undefined', gave the following error.
    Argument of type '(event: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(event: KeyboardEvent) => void' is not assignable to type 'EventListener'.
        Types of parameters 'event' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, charCode, code, ctrlKey, and 17 more.ts(2769)

Being a novice in typescript and not frequently programming on the front-end, I am unsure of what is causing this issue, particularly since I mostly relied on solutions found here on stackoverflow. Does anyone have insights into why this is happening?

Answer №1

To ensure TypeScript recognizes the events and properties of an element, you can utilize a generic parameter when using document.querySelector.

const bar_input = document.querySelector<HTMLInputElement>(".bar");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

Perform a series of database queries one after the other, ensuring they are completed before

Although the database queries themselves are working fine, I am facing an issue with executing them sequentially in Node. Here is an example of the queries I need to execute in order: DELETE FROM myTable; INSERT INTO myTable(c1, c2, c3) VALUES (x, y, z); ...

Issue: When a function within a subscribe method does not return a value and its declared type is not 'void' or 'any', a TypeScript error occurs

In my Angular 2 project, I've created a basic service to check if the user is logged in. This service verifies the existence of the user object within the FirebaseAuth object. However, I encountered an error stating "lack of return statement" even tho ...

The value of the filename property cannot be determined as it is undefined

Hey everyone, I'm currently working on a project using nestjs and reactjs. I encountered an error when trying to add a document that reads: "Cannot read properties of undefined (reading 'filename') in multer.config.ts" import { diskStorag ...

Typescript errors in console not being displayed by swc-loader

I have decided to make the switch from ts-loader to swc-loader based on the guidance provided in this article. However, after completing the migration, I am encountering an issue where basic Typescript errors are not being displayed in the console. For ins ...

Verify if a given string exists within a defined ENUM in typescript

I have an enum called "Languages" with different language codes such as nl, fr, en, and de. export enum Languages { nl = 1, fr = 2, en = 3, de = 4 } Additionally, I have a constant variable named "language" assigned the value 'de'. My g ...

Issue with TypeScript not detecting exported Firebase Cloud Functions

Dealing With Firebase Cloud Functions Organization I am managing a large number of Firebase Cloud Functions, and in order to keep the code well-structured, I have divided them into separate files for each function category (such as userFunctions, adminFun ...

Vue 3 Electron subcomponents and routes not displayed

Working on a project in Vue3 (v3.2.25) and Electron (v16.0.7), I have integrated vue-router4 to handle navigation within the application. During development, everything works perfectly as expected. However, when the application is built for production, the ...

Is it considered appropriate to return null in a didReceiveResponse callback function?

In my implementation, I have a callback called didReceiveResponse within a class that extends RESTDataSource. In this method, I return null when the response status is 404. However, due to the typing definition of RESTDataSource.didReceiveResponse, it seem ...

An issue occurred in React 16.14.0 where the error "ReferenceError: exports is not defined" was not properly

As the creator of the next-translate library, I have encountered a perplexing issue with an experimental version involving an error specifically related to React 16.14.0. Interestingly, upgrading React to version 17 resolves the issue, but I am hesitant to ...

Tips on using class-validator @isArray to handle cases where only a single item is received from a query parameter

Currently, I am attempting to validate a request using class-validator to check if it is an array. The inputs are sourced from query parameters like this: /api/items?someTypes=this This is what my request dto resembles: (...) @IsArray() @IsEn ...

I am eager to perform DOM manipulation similar to jQuery but within the context of Angular 6

Is there a way to modify the background color of the main div when a button is clicked? <div> <p>I'd like to be able to change the background color of the parent div by clicking a certain button. </p> <button (click)=" ...

Script - Retrieve the content of the code element

I am currently developing an extension for VS Code that will enhance Skript syntax support. One challenge I am facing is the inability to select the body of the code block. Skript syntax includes various blocks such as commands, functions, and events, eac ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

Steps to generate an accurate file order using Typescript:

Consider the scenario with two typescript files: In File a.ts: module SomeModule { export class AClass { } } And in File b.ts: module SomeModule { export var aValue = new AClass(); } When compiling them using tsc -out out.js b.ts a.ts, there are ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

ViewChild with the focus method

This particular component I'm working on has a hidden textarea by default : <div class="action ui-g-2" (click)="toggleEditable()">edit</div> <textarea [hidden]="!whyModel.inEdition" #myname id="textBox_{{whyModel.id}}" pInputTextarea f ...

The Angular Component utilizes the ng-template provided by its child component

I am currently facing an issue that involves the following code snippet in my HTML file: <form-section> <p>Hello</p> <form-section> <ng-template test-template> TEST </ng-template> ...

A guide on combining two native Record types in TypeScript

Is it possible to combine two predefined Record types in TypeScript? Consider the two Records below: var dictionary1 : Record<string, string []> ={ 'fruits' : ['apple','banana', 'cherry'], 'vegeta ...

Trouble with querying NG elements using "queryAll(By.css)" in Angular and Jasmin unit testing

I've encountered an unusual problem that needs to be resolved for me to successfully complete a unit test for a project I'm currently engaged in. Here is what my unit test currently looks like: it('should display the navbar list', ...