Imagine you have an array stored as a string in session storage, and you need to retrieve it, add an element, and then save it back.
trackNavHistory = (path: String) => {
let historyArr : Array<String> = sessionStorage.getItem("navHistory")?.split(",");
historyArr.push(path)
sessionStorage.setItem(JSON.stringify(historyArr));
}
The goal is to have historyArr as an array of strings fetched from sessionStorage.
However, the issue arises with the error message:
Type 'string[] | undefined' is not assignable to type 'String[]'.
Type 'undefined' is not assignable to type 'String[]'
This prevents setting the item back correctly.
An alternative attempt was made with the code snippet:
trackNavHistory = (path: String) => {
let historyArr : Array<String> = JSON.parse(sessionStorage.getItem("navHistory"));
historyArr.push(path)
sessionStorage.setItem(JSON.stringify(historyArr));
}
Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.ts(2345)