Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

I am playing around with typescript and am trying to create a script that will update a p-element as text is inputted in a input box.

The html looks as following:

<html>     <head>     </head>     <body>         <p id="greet"></p>         <form>             <input id="name" type="text" name="name" value="" onkeyup="greet('name')" />         </form>     </body>     <script src="greeter.js"></script> </html> 

And the greeter.ts file:

function greeter(person) {     return "Hello, " + person; }  function greet(elementId) {     var inputValue = document.getElementById(elementId).value;      if (inputValue.trim() == "")         inputValue = "World";      document.getElementById("greet").innerText = greeter(inputValue); } 

When I compile with tsc I get the following "error":

/home/bjarkef/sandbox/greeter.ts(8,53): The property 'value' does not exist on value of type 'HTMLElement'

However the compiler does output a javascript file, which works just fine in chrome.

How come I get this error? And how can I fix it?

Also, where can I look up which properties are valid on a 'HTMLElement' according to typescript?

Please note I am very new to javascript and typescript, so I might be missing something obvious. :)

like image 950
Bjarke Freund-Hansen Avatar asked Oct 20 '12 15:10

Bjarke Freund-Hansen


People also ask

Does not exist on type HTMLElement?

The error "Property 'value' does not exist on type 'HTMLElement'" occurs when we try to access the value property on an element that has a type of HTMLElement . To solve the error, use a type assertion to type the element as HTMLInputElement before accessing the property. This is the index.

What is HTMLInputElement?

The HTMLInputElement interface provides special properties and methods for manipulating the options, layout, and presentation of <input> elements.


1 Answers

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.

like image 93
Bjarke Freund-Hansen Avatar answered Oct 09 '22 17:10

Bjarke Freund-Hansen