ColorFlowing
ColorFlowing

Reputation: 64

Typecasting in JavaScript - HTMLElement vs HTMLInputElement

I've started maintaining a svelte project based on the sveltekt framework with pure JavaScript code as opposed to TypeScript.

When using VS Code, the following code (reduced to example) throws an error in the editor, but obviously works fine in practice. We know the element being targeted is definitely a HTMLInputElement, which has a value property:

let el = document.getElementById("inputelement");
processData(el.value);
Property 'value' does not exist on type 'HTMLElement'.js(2339)

I thought assigning a type via JSDoc would fix this, but it throws a different error:

/**
 * @type {HTMLInputElement}
*/
let el = document.getElementById("inputelement");
Type 'HTMLElement' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 53 more.js(2740)

This being JavaScript, I know I can't assign a type like I would in TypeScript (<HTMLInputElement> or as HTMLInputElement), but I'd like to avoid using @ts-ignore to skip the line of code entirely.

What am I missing? Is there a svelte equivalent to comment types like Flow allows?

Edit: Thanks to the help in comments on this question, assigning a type with an inline type declaration works. This is the code:

let el = /** @type {HTMLInputElement} */ (document.getElementById("inputelement"));
processData(el.value);

Upvotes: 0

Views: 1026

Answers (1)

ColorFlowing
ColorFlowing

Reputation: 64

Thanks to the help in comments on this question! An inline type assertion comment works to get rid of the error message.

This is the code:

let el = /** @type {HTMLInputElement} */ (document.getElementById("inputelement"));
processData(el.value);

Upvotes: 1

Related Questions