I'm currently trying to get the values a user would insert into an input form. In vanilla javascript, I can just target the element by id or class, etc, and then I can just use the .value method to actually get in use that method. For some reason, typescript cannot do that, which I do not understand because typescript is a superset of javascript. Is there a specific way to get a value from an input element in pure typescript or do I have to use angular or something?
Typescript code:
interface IUserFoodOptions {
food: string;
calories: number;
foodDate: any;
}
class Food implements IUserFoodOptions {
food: string;
calories: number;
foodDate: any;
// store all the calories in an array and calculate the total amount of calories
caloriesArray: number[] = [];
// constructor
constructor(food: string, calories: number, foodDate: any) {
this.food = food;
this.calories = calories;
this.foodDate = foodDate;
}
}
// event listener for when the add food button is clicked
let addFood = document.getElementById("add-food-button").addEventListener("click", () => {
// get the values from inputs and store them in an array
let foodName = document.getElementById("food-name-val");
let foodCalories = document.getElementById("calories-val");
let dateVal = document.getElementById("date-val");
// store these values in a list and display them below
// user will have the ability to edit and delete them
// am I create event listeners within event listeners
});
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;