TS Warning In JS File: "Property X Does Not Exist On Type X": Is It Possible To Write Cleaner JavaScript?
Solution 1:
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.
Post a Comment for "TS Warning In JS File: "Property X Does Not Exist On Type X": Is It Possible To Write Cleaner JavaScript?"