Javascript 使用TS从localstorage强制转换检索到的对象

Javascript 使用TS从localstorage强制转换检索到的对象,javascript,typescript,Javascript,Typescript,const[history,setHistory]=useState(localStorage.getItem('history')|{}) TS不再知道什么是历史记录类型,一旦我将其保存在localstorage中并检索回来,我如何重新分配该类型?这样我就可以像这样使用它 JSON.parse(history).id不幸的是,localStorage.getItem返回一个字符串或空值-在解析完JSON后,如果没有类型转换/类型断言,就无法真正注入字符串的类型 我将围绕localStorage

const[history,setHistory]=useState(localStorage.getItem('history')|{})

TS不再知道什么是历史记录类型,一旦我将其保存在localstorage中并检索回来,我如何重新分配该类型?这样我就可以像这样使用它


JSON.parse(history).id

不幸的是,
localStorage.getItem
返回一个字符串或空值-在解析完JSON后,如果没有类型转换/类型断言,就无法真正注入字符串的类型

我将围绕
localStorage.getItem
制作一个包装器,它解析
localStorage
中的字符串并返回正确类型的对象:

const getHistory = () => {
    const json = localStorage.getItem('x') ?? '{}';
    return JSON.parse(json) as { id?: number };
    // replace number type above with whatever is needed
};
// ...

// Retrieve initial history only once, not on every render:
const initialHistory = getHistory();
const App = () => {
    const [history, setHistory] = useState(initialHistory);

请注意,使用这种方法,
history
变量是类型化的对象,而不是字符串(这可能是可取的,这样会更容易使用)。

您可以发布更多的代码吗?什么是
localStorageGet
,您需要在哪里“重新分配类型”?
localStorageGet
返回什么类型?@zerkms localstorage的历史记录