Argument of type 'string | number | string[] | undefined' is not assignable to parameter of type 'string' when converting JavaScript to TypeScript

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.


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.