Getting the value from <input> element in typescript
Yeah, TypeScript has this "little issue", but it is for safety.
You can get the input value doing something like this:
var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;
You can see more about this casting <> thing here: TypeScript: casting HTMLElement
Hope it works!
If you are using an editor like VSCode to write Typescript, I've found the ability to inspect code very valuable in learning more about what's occurring in the typing system. In VSCode you can right click on the method(or type) and choose Go to definition
.
Inspecting the method in your question, getElementById
, you can see it returns an HTMLElement
. This type doesn't have a value
property on it. This makes sense as getElementById
can return any HTMLElement
on the page as long as it has an id
attribute. Not every HTMLElement
though has a value
property(for instance a div
/span
/p
, etc).
Since you know what type you are expecting, but the type system can't, to get this to work, you have to tell Typescript what type of element you expect to be selecting. You would do that through casting the type of the selected element as follows:
const inputElement = <HTMLInputElement> document.getElementById("food-name-val");
or
const inputElement = document.getElementById("food-name-val") as HTMLInputElement;
Now, since Typescript recognizes the selected element as an HTMLInputElement
, it won't error when you access the value
property on it.
In your case that would look like:
let foodName = (document.getElementById("food-name-val") as HTMLInputElement).value;