I am currently discovering TypeScript. I use the following code:
const someClass = document.querySelector(".that-class");
const someId = document.getElementById("elemId").value;
As many others before me and surely many more to come I am getting the following errors:
Property 'style' does not exist on type 'Element'.
Property 'value' does not exist on type 'HTMLElement'.
I fixed these errors in my .ts file by adding <HTMLElement> or <HTMLInputElement> when needed, works fine. But when I compile my .ts I get some TS warnings from VSCode in the .js file.
My question is simply: is there a way to avoid getting these errors in the JS file as well (i.e.: is there a "cleaner" way to write JavaScript code)? Or should I simply ignore these TS warnings?
Thanks very much for your help!
Some good news here: I found the answer I was looking for.
To give you some additional context: I was working with a form and needed to manipulate some user inputs using JavaScript/TypeScript. This is the code:
<form id="my-form" action="index.html" method="get" onsubmit="return showValue();">
<input type="text" name="username">
<input type="text" name="full-name">
<input type="password" name="password">
<button type="button" onclick="showValue();">Send</button>
</form>
And my JavaScript code:
function showValue() {
const myForm = document.getElementById("my-form").value;
console.log(myForm);
return 1;
}
Which would return the warning: "Property 'value' does not exist on type 'HTMLElement'.
This can easily be fixed by adding some variation of this code in TypeScript:
const myForm = (<HTMLInputElement>document.getElementById("my-form")).value;
Great, no more warning in TypeScript. But after compiling it the resulting JavaScript file would again show the warning: "Property 'X' does not exist on type X"
My question hence was, how do I write my code so that I don't get any warning AT ALL ?
I hopefully found the answer as following:
function showValue() {
const myForm = document.forms.my-form;
console.log(myForm?.username.value);
return 1;
}
It took me quite a while to find it and some digging in specifications docs but hopefully this seems to work!
I still want to thank you all for your comments, they helped a lot in my way to finding the answer.