What is the method for documenting the on:input event triggered by the HTML Input element in Svelte using JSDoc?

When I try to define an event that I receive from a Svelte-managed input element, TypeScript informs me that my JSDoc type does not match what I receive from the on:input. On my page, I have an input field with the following handler:

<input id="description" on:input={handleInput}

And in my JavaScript code, I wrote:

/** @param {InputEvent & { target: HTMLInputElement}} event */
const handleInput = (event) => {
  const fullInput = event.target.value;
  const singleChar = event.data;
  const cursorPosition = event.target.selectionStart;
  // ...

The types are recognized correctly within handleInput(). However, TypeScript raises an error for on:input in the HTML:

Type '(event: InputEvent & {    target: HTMLInputElement;}) => void' is not assignable to type 'FormEventHandler<HTMLInputElement>'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'Event & { currentTarget: EventTarget & HTMLInputElement; }' is not assignable to type 'InputEvent & { target: HTMLInputElement; }'.
      Type 'Event & { currentTarget: EventTarget & HTMLInputElement; }' is missing the following properties from type 'InputEvent': data, dataTransfer, inputType, isComposing, and 5 more.js(2322)

Why do these types clash and is there any solution to this issue?

Answer №1

When documenting an oninput event in JavaScript using JSDoc, there are three different ways to approach it. Particularly, if you are assigning your function to a variable (e.g.

const func = () => "hello"
, also known as a function expression), you cannot utilize the JSDoc @param keyword. Instead, you must employ the special JSDoc function expression syntax as demonstrated in the examples below.

► For a function expression as the event handler:

/**@type{(event:Event)=>void}*/
const handleInput = event => {
  // do stuff...
};

► Another way for function expression syntax:

/**@type{function(Event):void}*/
const handleInput = event => {
  // do stuff...
};

► Lastly, for a function declaration as the event handler:

/**
 * @param {Event} event
 * @return void
 */
function handleInput(event) {
  // do stuff...
}

Answer №2

Here is the recommended JSDoc @param definition:

/** @param {Event & {currentTarget: EventTarget & HTMLInputElement} & {target: HTMLInputElement} & InputEvent} event */

Context: Make the switch from using :input to on:input={(e)=> e } and hover over e. This will provide you with the exact expected type (ready for copying and pasting into JSDoc @param).

In this particular instance, it involved:

{Event & {currentTarget: EventTarget & HTMLInputElement}

By implementing this solution, the TS error related to on:input was resolved. However, new TS errors arose in relation to:

const fullInput = event.target.value;
const singleChar = event.data;
const cursorPosition = event.target.selectionStart;

The issue here lies in the fact that .data and .target are not properties of Event, but rather belong to InputEvent. For further clarification on why Svelte opts out of using InputEvent, refer to this explanation. Furthermore, .target should be designated as HTMLInputElement (akin to .currentTarget). Introducing

& {target: HTMLInputElement} & InputEvent
rectifies these discrepancies, thus silencing TS complaints. Whether or not this method is considered best practice remains up for debate.

Hoping this insight proves beneficial to others. Special thanks to Mike 'Pomax' Kamermans, jonrsharpe, and the Svelte Discord channel.

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

Step-by-step guide on sorting WordPress posts by a custom field date

I've created an event sidebar section that will only show the next 3 upcoming events. I have successfully set up the custom post type and custom fields, but I am struggling to figure out how to order the posts based on the start date of the events, wh ...

Retrieve an element within a jQuery each loop

I'm currently implementing AJAX functionality to retrieve cart items from the server and display them within a cart when a customer clicks on the "My Cart" button. Here is the model for the cart: public class Cart { [Key] public i ...

What is the best way to align a badge icon regardless of the avatar's size?

I'm working on creating an avatar component with badges. However, I'm facing an issue with the positioning of the badges relative to the avatar size. The image below provides a clear illustration of the problem. Can you guide me on adjusting the ...

What is causing my click event, which I included in a table row, to not function properly?

I'm having trouble with this code I wrote. When I click on a row in the table (tr tag), nothing happens and I can't figure out why... readDetails(){ this.router.navigate(['/dettaglio-contributivo']); console.log("It should work ...

Browser continuously misplaces JavaScript file

My new computer running Windows 8 is giving me a headache. I installed xampp and an apache server, created a basic HTML page with JavaScript and jQuery. Everything was running smoothly until I refreshed the page and suddenly my browser couldn't find t ...

How can you start a jQuery script following a triumphant Ajax callback?

Having some trouble getting jQuery to execute after a successful Ajax response. Even though I have it in the success callback, it doesn't seem to be working as expected. I came across a potential solution here, but I'm having difficulty understan ...

Mesh object circling in the opposite direction of the displayed image

Working on replicating a Flash website using Three.JS and facing difficulty in achieving desired functionality. The goal is to create button images that orbit around the center of the screen, stop when hovered over by the mouse, and open a different locat ...

What is the best way to utilize *ngSwitchWhen in a TypeScript environment?

I am currently working with Ionic2 and Angular2 and encountering an issue while trying to implement a segment using ngSwitchWhen. Unfortunately, the functionality is not working as expected and I am receiving an error message. How can I resolve this issue ...

Tips for addressing the issue of FormControlName being duplicated for every row in reactive forms

My reactive form contains columns and rows that can be dynamically added. However, when inspecting the form and adding multiple rows, the formControlName attribute repeats for each row. I am looking for a solution to have incrementing formControlNames for ...

Update the content within a document and implement jQuery to make it clickable

Within my webpage, there is a random occurrence of the word -FORM-. I am looking to replace this word with another text that includes dashes for creating a clickable div. Despite having some code that successfully replaces the text, it lacks the function ...

Importing data from an external file into an array using AngularJS

Hey there, I'm new here on Stack and hoping someone can lend a hand because I've hit a roadblock! I'm working with an AngularJS script that generates multiple icons using data from a simple array. Each icon is linked to a YouTube video. Th ...

Why am I receiving an error message stating "undefined is not a function" when trying

I am attempting to create a popover using the Angular UI pop over feature. I have loaded my HTML and compiled it, but when I run my program and click on the star icon (where I display the popover), I receive an error stating that 'undefined is not a f ...

Encountered a 'File is not defined' error in JavaScript when running code from the node.js command line

I'm encountering an issue with my JavaScript code that is supposed to read a file and print it on the console. Despite having the file test.txt in the same path, I keep getting an error saying "File is not defined." Below is the snippet of the code: ...

What is the best way to find the maximum and minimum values within a JSON object that is populated from user inputs using only JavaScript?

Here is a simple form that stores data at the following link: https://jsfiddle.net/andresmcio/vLp84acv/ var _newStudent = { "code": code, "names": names, "grade": grades, }; I'm struggling to retrieve the highest and lowe ...

What steps can I take to ensure that the upper and left sections of a modal dialog remain accessible even when the size is reduced to the point of overflow?

One issue I'm facing is with a fixed-size modal dialog where part of the content gets cut off and becomes inaccessible when the window shrinks to cause an overflow. More specifically, when the window is narrowed horizontally, the left side is cut off ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

An angular component that is functioning properly when connected to a live server, however, it is experiencing issues when trying to run `

I tried integrating versitka into my Angular component by placing the version HTML file and all necessary assets in the appropriate directories. However, when I run ng serve, only the HTML file seems to be working, while the CSS and images fail to load. I ...

What is the method for entering text into a span element and submitting it by hitting the "ENTER" key using Selenium in Python 3.7?

Environment: Using Python 3.7 and Selenium 3.141 Issue : I need to automate commenting on posts using Selenium in a web page. The challenge is that the comment form does not have a traditional "Submit" button; instead, it's a SPAN element where yo ...

Exploring the relationships between schemas in Node.js using Mongoose and MongoDB

Hello, I am a beginner in utilizing MongoDB and Node.js and I have a query. Below is my product schema: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const categorySchema = require('./category'); const Produc ...

Creating a selection area with CSS that appears transparent is a straightforward process

I'm currently exploring ways to implement a UI effect on a webpage that involves highlighting a specific area while covering the rest of the page with a semi-transparent black overlay, all using CSS only. What is the most common approach to achieving ...