[英]cast retrieved object from localstorage with TS
const [history, setHistory] = useState(localStorage.getItem('history') || {});
一旦我將它保存在本地存儲中並取回它,TS 就不再知道歷史類型是什么了,我該如何重新分配類型? 這樣我就可以像
JSON.parse(history).id
不幸的是, localStorage.getItem
返回一個字符串或 null - 在沒有類型轉換/類型斷言的情況下,你不能在字符串被 JSON 解析后真正注入字符串的類型。
我會在localStorage.getItem
周圍做一個包裝器,它解析localStorage
中的字符串並返回正確類型的 object:
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
變量是類型化的 object ,而不是字符串(這可能是可取的 - 它會更容易使用)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.