I’m trying to covert the following JavaScript function to TypeScript and I’m getting the following error
$("#checkoutSubmit").click(function () {
var departureDate = $("#bookingDepartureDateInput").val();
localStorage.setItem("datevalue", departureDate);
console.log(localStorage.getItem("datevalue"))
});
I’ve never used TypeScript and I seem to be struggling with converting this. Can I get some insight on how to rewrite this code in TypeScript? Thank you.
>Solution :
the JQuery val(); method can return a String, Number or Array<string> this causes an error because localStorage.setItem only accepts strings.
If you are sure that $("#bookingDepartureDateInput").val(); always returns a string you can use as string to tell typescript that it can assume it will be a string:
$("#checkoutSubmit").click(function () {
const departureDate = $("#bookingDepartureDateInput").val() as string;
localStorage.setItem("datevalue", departureDate);
console.log(localStorage.getItem("datevalue"))
});
JQuery .val() docs.
