簡體   English   中英

演員使用 TS 從本地存儲中檢索到 object

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM