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.
CodePudding user response:
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.
CodePudding user response:
The jQuery val method returns string, string[], number, or undefined. But you're trying to use it with the storage interface's setItem method, which only accepts strings. So you get an error, since that may be a mistake.
If you know that the value from val will be a string, while you could just do as string on it, the problem with that is you're making an assumption that you aren't checking: that nothing will make that claim (a type assertion) untrue. Instead, you could use a type assertion function to reassure TypeScript and ensure that the condition is correct:
function assertIsString(value: any): asserts value is string {
if (typeof value !== "string") {
throw new Error(`String expected, got non-string instead`);
}
}
The the code would be:
$("#checkoutSubmit").click(function () {
const departureDate = $("#bookingDepartureDateInput").val();
assertIsString(departureDate);
localStorage.setItem("datevalue", departureDate);
console.log(localStorage.getItem("datevalue"))
});
That works because after the assertion function call, TypeScript knows it has a string.

