TypeScript Version: 1.8.10
Code
var inputFields = document.getElementsByClassName("settings");
localStorage.setItem("someOption", inputFields[1].value);
// TS says "value" is unknown
// plain JS says no problem here
Expected behavior:
compile without a problem
Actual behavior:
doesn't compile when you start the compiling process with the "error" in the file but it works if the process is running and afterwards you add the erroneous line to your code!
The return type of getElementsByClassName
is probably something like 'HTMLElement', which is a base interface. HTMLInputElement, which extends it, is where .value
lives. Same story for HTMLSelectElement, etc. You'll want to cast to that more specific interface.
To be clear, the fix is to use a type assertion.
let inputFields = document.getElementsByClassName("settings") as HTMLDivElement
I also agree with @jwbay
Having an issue https://github.com/Microsoft/TypeScript/issues/15047, but its a bit unrelated.
@DanielRosenwasser the code snippet in your comment should be:
let inputFields = document.getElementsByClassName("settings") as HTMLInputElement
(HTMLInputElement
rather than HTMLDivElement
... hence the down-votes on your answer (I suspect))
Other than that, thanks for the answer! This got me out of a bind.
We can use something like this
const elem: HTMLInputElement =<HTMLInputElement>document.getElementById('element id');
const value: string = elemvalue;
Most helpful comment
@DanielRosenwasser the code snippet in your comment should be:
(
HTMLInputElement
rather thanHTMLDivElement
... hence the down-votes on your answer (I suspect))Other than that, thanks for the answer! This got me out of a bind.