0

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);
  • https://stackoverflow.com/questions/12989741/the-property-value-does-not-exist-on-value-of-type-htmlelement – Irakli Tchedia Sep 20 '22 at 08:56
  • Thanks for your reply @IrakliTchedia , but the project is not using TypeScript, which stops me from using any of its assertion syntax as a solution to this issue. – ColorFlowing Sep 20 '22 at 09:11
  • Have you tried using `@type` inline instead of in the JSDoc of the variable? – H.B. Sep 20 '22 at 09:18
  • Not until now, but the inline comment seems to be ignored. Edit: ```processData(/** @type {HTMLInputElement} */ el.value);``` – ColorFlowing Sep 20 '22 at 09:31
  • When using inline comments, you need to surround the following expression in brackets: `/** @type {HTMLInputElement} */ el.value` -> `/** @type {HTMLInputElement} */ (el.value)`. It's [a poorly documented design decision](https://github.com/microsoft/TypeScript/issues/18212). EDIT: with that said, I don't think `el.value` would return an HTMLInputElement EDIT2: unless you wanted `/** @type {HTMLInputElement} */ (el).value` – VLAZ Sep 20 '22 at 09:34
  • Right. that does work! Thank you both for the idea and the syntax help. It works like this ```let el = /** @type {HTMLInputElement} */ (document.getElementById("inputelement"));``` – ColorFlowing Sep 20 '22 at 09:38

1 Answers1

1

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);