Typescript: error TS2339: Property 'value' does not exist on type 'Element' (BUT IT EXISTS!)

Created on 20 Aug 2016  ·  5Comments  ·  Source: microsoft/TypeScript

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!

Working as Intended

Most helpful comment

@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.

All 5 comments

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;

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fwanicka picture fwanicka  ·  3Comments

Antony-Jones picture Antony-Jones  ·  3Comments

Roam-Cooper picture Roam-Cooper  ·  3Comments

zhuravlikjb picture zhuravlikjb  ·  3Comments

dlaberge picture dlaberge  ·  3Comments