The property 'value' does not exist on value of type 'HTMLElement'

Try casting the element you want to update to HTMLInputElement. As stated in the other answers you need to hint to the compiler that this is a specific type of HTMLElement:

var inputElement = <HTMLInputElement>document.getElementById('greet');
inputElement.value = greeter(inputValue);

Based on Tomasz Nurkiewiczs answer, the "problem" is that typescript is typesafe. :) So the document.getElementById() returns the type HTMLElement which does not contain a value property. The subtype HTMLInputElement does however contain the value property.

So a solution is to cast the result of getElementById() to HTMLInputElement like this:

var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;

<> is the casting operator in typescript. See the question TypeScript: casting HTMLElement.

If you're in a .tsx file the casting syntax above will throw an error. You'll want to use this syntax instead:

(document.getElementById(elementId) as HTMLInputElement).value

The resulting javascript from the line above looks like this:

inputValue = (document.getElementById(elementId)).value;

i.e. containing no type information.


We could assert

const inputElement: HTMLInputElement = document.getElementById('greet')

Or with as-syntax

const inputElement = document.getElementById('greet') as HTMLInputElement

Giving

const inputValue = inputElement.value // now inferred to be string

If you are using react you can use the as operator.

let inputValue = (document.getElementById(elementId) as HTMLInputElement).value;

Tags:

Typescript