TypeScript 與 Web Storage

TypeScript 與 Web Storage

本文說明 TypeScript 與 Web Storage。

我們將解說 TypeScript 與 Web Storage,並包含實用範例。

YouTube Video

TypeScript 與 Web Storage

瀏覽器的 Web Storage 是針對字串的鍵值儲存。它很輕量,提供同步 API,但請注意它僅能儲存字串,並且你必須處理例外,例如超出儲存配額。結合 TypeScript 後,你可以加入型別安全安全的序列化/反序列化集中式鍵管理,以及到期與版本管理,打造生產等級的設計。

localStoragesessionStorage

localStorage 為關閉瀏覽器後仍保留的永續儲存;sessionStorage 則是以分頁/視窗為單位的工作階段儲存,關閉分頁時會被清除。兩者皆以鍵值對(字串)儲存資料。

1// Simple usage example: store and retrieve a string
2// This example uses localStorage to persist a username.
3localStorage.setItem('username', 'alice');
4console.log('saved username:', localStorage.getItem('username')); // "alice"
5
6// session storage example
7sessionStorage.setItem('session-id', 'xyz-123');
8console.log('session id:', sessionStorage.getItem('session-id')); // "xyz-123"
  • 這段程式碼示範如何儲存與讀取字串。由於 Web Storage 只能儲存字串,物件必須轉為 JSON 才能儲存。

使用 JSON 解析的範例

Web Storage 中儲存與還原物件時,使用 JSON.stringify / JSON.parse

1// Simple write & read with JSON
2// Store a small object as JSON and read it back.
3const user = { id: 1, name: "Alice" };
4localStorage.setItem("app:user", JSON.stringify(user));
5
6const raw = localStorage.getItem("app:user");
7const parsed = raw ? (JSON.parse(raw) as { id: number; name: string }) : null;
8
9console.log("user:", parsed); // user: { id: 1, name: "Alice" }
  • 這段程式碼是最小可運作範例。在實際應用中,你也必須考量解析失敗與儲存配額用盡等例外。

JSON 解析的例外處理範例

在此我們提供一個包裝器,使讀寫更安全,並處理 JSON.parse 失敗與 setItem 的例外。

 1// Safe JSON helpers
 2// These helpers handle parse errors and memory/storage issues separately.
 3export function safeParseJson<T>(raw: string | null): T | null {
 4  if (raw == null) return null;
 5
 6  try {
 7    return JSON.parse(raw) as T;
 8  } catch (error: any) {
 9    if (error instanceof SyntaxError) {
10      console.error("JSON parse error:", error.message);
11      return null;
12    }
13
14    console.error("Unexpected JSON error:", error);
15    return null;
16  }
17}
18
19// Safe setter for JSON values
20export function setJson(storage: Storage, key: string, value: unknown): void {
21  try {
22    const json = JSON.stringify(value);
23    storage.setItem(key, json);
24  } catch (error: any) {
25    if (error?.name === "QuotaExceededError") {
26      console.error("Storage quota exceeded while saving JSON:", error.message);
27    } else if (error instanceof TypeError) {
28      console.error("JSON serialization failed:", error.message);
29    } else {
30      console.error("Unexpected error while setting JSON:", error);
31    }
32  }
33}
34
35// Safe getter for JSON values
36export function getJson<T>(storage: Storage, key: string, fallback?: T): T | null {
37  const parsed = safeParseJson<T>(storage.getItem(key));
38  return parsed ?? (fallback ?? null);
39}
  • 此工具可在整個應用程式中重複使用。想加入 try/catch 時可再進一步封裝。

含 TTL(到期)的儲存範例

由於 Web Storage 本身沒有 TTL,可在值中加入 expiresAt 來管理到期。

 1// TTL wrapper
 2// Store { value, expiresAt } and automatically expire items on read.
 3type WithTTL<T> = { value: T; expiresAt: number | null };
 4
 5export function setWithTTL<T>(storage: Storage, key: string, value: T, ttlMs?: number) {
 6  const payload: WithTTL<T> = { value, expiresAt: ttlMs ? Date.now() + ttlMs : null };
 7  setJson(storage, key, payload);
 8}
 9
10export function getWithTTL<T>(storage: Storage, key: string): T | null {
11  const payload = getJson<WithTTL<T>>(storage, key);
12  if (!payload) return null;
13  if (payload.expiresAt && Date.now() > payload.expiresAt) {
14    storage.removeItem(key);
15    return null;
16  }
17  return payload.value;
18}
  • TTL 對快取與自動儲存(草稿)很有效,並可降低不一致性。

集中化鍵管理與命名空間(避免衝突)的範例

將鍵標準化為 前綴 + 版本 + 名稱 可降低衝突並簡化遷移。

 1// Key factory with namespacing and versioning
 2// Create namespaced keys like "myapp:v1:theme" to avoid collisions.
 3const APP = "myapp";
 4const V = "v1";
 5
 6const ns = (k: string) => `${APP}:${V}:${k}`;
 7
 8const Keys = {
 9  theme: ns("theme"),
10  user: ns("user"),
11  cart: ns("cart"),
12  draft: ns("draft"),
13};
  • 在鍵中包含命名空間,可讓日後更容易切換版本或進行清理。

配額超限(QuotaExceededError)與後備策略的範例

請考量在執行 setItem 時可能發生 QuotaExceededError,並設計在儲存失敗時的後備策略。例如,當超出儲存容量時,你可以刪除舊資料,或改用 sessionStorage 或記憶體內快取作為後備,以維持整體應用的穩定性。

 1// Quota-safe set with fallback to in-memory storage
 2// Return true if stored, false otherwise.
 3export function trySetJson(storage: Storage, key: string, value: unknown, fallback?: Map<string, string>): boolean {
 4  try {
 5    storage.setItem(key, JSON.stringify(value));
 6    return true;
 7  } catch (err) {
 8    console.warn("Failed to set item:", key, err);
 9    if (fallback) {
10      try {
11        fallback.set(key, JSON.stringify(value));
12        return true;
13      } catch {
14        return false;
15      }
16    }
17    return false;
18  }
19}
20
21// Example fallback usage
22const inMemoryFallback = new Map<string, string>();
23const ok = trySetJson(localStorage, Keys.cart, { items: [] }, inMemoryFallback);
24if (!ok) console.log("Saved to fallback map instead");
  • 視後備目標而定,資料的持久性可能無法保證。因此,請依你的使用情境選擇合適的儲存目的地。例如,在私密瀏覽模式或受儲存限制時,你可以暫時使用記憶體或 sessionStorage 以維持功能。

跨分頁同步(storage 事件)與同分頁通知的範例

使用 window.addEventListener('storage', …),你可以偵測在其他分頁發生的儲存變更。不過,在同一個分頁內不會觸發此事件。因此,對於同分頁內的變更通知,請使用 CustomEvent 發佈自訂事件。

 1// Cross-tab and same-tab notification helpers
 2// storage event fires on other tabs; use CustomEvent for same-tab listeners.
 3const SAME_TAB_EVENT = "storage:changed";
 4
 5function notifyChanged(key: string) {
 6  window.dispatchEvent(new CustomEvent(SAME_TAB_EVENT, { detail: { key } }));
 7}
 8
 9function setJsonWithNotify(storage: Storage, key: string, value: unknown) {
10  setJson(storage, key, value);
11  notifyChanged(key);
12}
13
14// Listeners
15window.addEventListener("storage", (e) => {
16  if (e.key === Keys.theme) {
17    const theme = safeParseJson<string>(e.newValue);
18    console.log("Theme changed in another tab:", theme);
19  }
20});
21
22window.addEventListener(SAME_TAB_EVENT, (e: Event) => {
23  const detail = (e as CustomEvent).detail as { key: string };
24  console.log("Changed in this tab:", detail.key);
25});
  • 有了這段程式碼,你可以在其他分頁目前分頁之間同步儲存變更。

型別安全的註冊表(每個鍵皆有嚴格型別)

在 TypeScript 中定義鍵到型別的對映,以避免在儲存與讀取時出錯。

 1// Typed registry that enforces types per key
 2// Registry maps keys to their allowed types.
 3type Registry = {
 4  [k in typeof Keys.theme]: "light" | "dark";
 5} & {
 6  [k in typeof Keys.user]: { id: number; name: string };
 7};
 8
 9type KeyOf<R> = Extract<keyof R, string>;
10
11export const TypedStore = {
12  get<K extends KeyOf<Registry>>(key: K, storage: Storage = localStorage): Registry[K] | null {
13    return getJson<Registry[K]>(storage, key);
14  },
15  set<K extends KeyOf<Registry>>(key: K, value: Registry[K], storage: Storage = localStorage): void {
16    setJson(storage, key, value);
17  },
18  remove<K extends KeyOf<Registry>>(key: K, storage: Storage = localStorage): void {
19    storage.removeItem(key);
20  },
21};
  • {^ i18n_speak 型をキーに関連付けることで、ランタイムでの誤使用をコンパイル時に検出でき、安全性を高めることができます。 ^}

複雜型別的序列化/還原器(Date/Map 等)

若要正確還原 DateMap 等物件,請善用 JSON.stringifyreplacerreviver

 1// Serializing Dates with replacer and reviver
 2// Custom replacer marks Date objects for correct revival.
 3function replacer(_k: string, v: unknown) {
 4  if (v instanceof Date) return { __type: "Date", value: v.toISOString() };
 5  return v;
 6}
 7
 8function reviver(_k: string, v: any) {
 9  if (v && v.__type === "Date") return new Date(v.value);
10  return v;
11}
12
13function setJsonWithDates(storage: Storage, key: string, value: unknown) {
14  storage.setItem(key, JSON.stringify(value, replacer));
15}
16
17function getJsonWithDates<T>(storage: Storage, key: string): T | null {
18  const raw = storage.getItem(key);
19  if (!raw) return null;
20  try { return JSON.parse(raw, reviver) as T; } catch { return null; }
21}
  • 使用此方法,Date 物件會被正確還原為 Date。同樣地,MapSet 也可以被標記並還原。

版本化與遷移策略的範例

若未來可能更改儲存格式,請在載荷中包含版本並預備遷移。

 1// Versioned payload pattern for migrations
 2// Keep { v, data } and migrate on read if necessary.
 3type VersionedPayload<T> = { v: number; data: T };
 4
 5function migrateUserV1toV2(u1: { id: number; name: string }) {
 6  return { id: u1.id, profile: { displayName: u1.name } };
 7}
 8
 9function readUserAnyVersion(): { id: number; profile: { displayName: string } } | null {
10  const raw = localStorage.getItem(Keys.user);
11  if (!raw) return null;
12  try {
13    const obj = JSON.parse(raw) as VersionedPayload<any>;
14    if (obj.v === 2) {
15      return obj.data;
16    } else if (obj.v === 1) {
17      const migrated = migrateUserV1toV2(obj.data);
18      localStorage.setItem(Keys.user, JSON.stringify({ v: 2, data: migrated }));
19      return migrated;
20    }
21    return null;
22  } catch (err) {
23    console.error("migration parse error", err);
24    return null;
25  }
26}
  • 透過疊加小型遷移,可維持向後相容性。

在 SSR(伺服器端渲染)中的處理範例

在沒有 window 的環境中,直接參考 localStorage 會當機,請使用環境守衛進行判斷。

1// Guard for SSR
2// Return a Storage-compatible object or null when not in browser.
3export const isBrowser = (): boolean => typeof window !== "undefined" && typeof window.localStorage !== "undefined";
4
5export const safeLocalStorage = (): Storage | null => (isBrowser() ? window.localStorage : null);
6
7// Usage
8const ls = safeLocalStorage();
9if (ls) setJson(ls, Keys.theme, "dark");
  • 對需支援 SSR 的程式碼,務必記得檢查 typeof window

實用提示

  • 使用去抖/節流(debounce/throttle)限制寫入頻率,以緩解 UI 動作造成的突發。
  • 以命名空間 + 版本管理鍵,例如:app:v1:...
  • 原則上不要儲存敏感資訊(存取權杖等)。如非存不可,請考慮短有效期並搭配伺服器驗證或 WebCrypto。
  • 容量取決於瀏覽器(數 MB),大型資料請存於 IndexedDB。
  • 同分頁通知使用 CustomEvent,跨分頁使用 storage
  • 在 SSR 中,務必檢查 typeof window

整合版 '型別安全儲存' 類別

讓我們看看一個泛型類別的範例實作,它整合了目前為止我們涵蓋的要素,包括命名空間、型別安全、有效期限(TTL)以及例外處理。在實際產品中,請考慮加入測試、記錄、基於 LRU 的舊資料刪除、加密等。

 1// Comprehensive TypedStorage store integrating many patterns shown above.
 2// - type-safe registry per key
 3// - prefix (namespace + version)
 4// - trySet with fallback
 5// - same-tab notify
 6// - TTL optional getter/setter
 7type Jsonifiable = string | number | boolean | null | Jsonifiable[] | { [k: string]: Jsonifiable };
 8
 9interface StoreOptions {
10  storage?: Storage | null;   // default: auto-detected localStorage or null
11  prefix?: string;            // e.g., "myapp:v1"
12  sameTabEvent?: string | null;
13  fallback?: Map<string, string>; // in-memory fallback
14}
  • 這段程式碼展示了建置型別安全、功能豐富的鍵值儲存所需的設定與型別定義。
 1export class TypedStorage<Reg extends Record<string, Jsonifiable | object>> {
 2  private storage: Storage | null;
 3  private prefix: string;
 4  private sameTabEvent: string | null;
 5  private fallback?: Map<string, string>;
 6
 7  constructor(private registry: Reg, opts: StoreOptions = {}) {
 8    this.storage = opts.storage ?? (typeof window !== "undefined" ? window.localStorage : null);
 9    this.prefix = (opts.prefix ?? "app:v1") + ":";
10    this.sameTabEvent = opts.sameTabEvent ?? "storage:changed";
11    this.fallback = opts.fallback;
12  }
13
14  private k(key: keyof Reg & string) { return this.prefix + key; }
  • 這段程式碼是 TypedStorage 類別的核心,它提供型別安全的鍵值儲存。它根據 registry 管理允許的鍵及其型別,並產生帶有前綴的儲存鍵。此外,它使用 localStorage 與記憶體內的後備,並允許設定同分頁變更通知的事件名稱。
 1  // Basic get with optional TTL-aware retrieval
 2  get<K extends keyof Reg & string>(key: K): Reg[K] | null {
 3    const fullKey = this.k(key);
 4    try {
 5      const raw = this.storage ? this.storage.getItem(fullKey) : this.fallback?.get(fullKey) ?? null;
 6      if (!raw) return null;
 7      // Check if value is TTL-wrapped
 8      const maybe = safeParseJson<{ value: Reg[K]; expiresAt?: number }>(raw);
 9      if (maybe && typeof maybe.expiresAt === "number") {
10        if (maybe.expiresAt && Date.now() > maybe.expiresAt) {
11          this.remove(key);
12          return null;
13        }
14        return maybe.value;
15      }
16      return safeParseJson<Reg[K]>(raw);
17    } catch (err) {
18      console.error("TypedStorage.get error", err);
19      return null;
20    }
21  }
  • get 方法以型別安全的方式取得指定鍵的值,並可選擇性地處理具有 TTL(有效期限)的值。
 1  // Basic set; returns success boolean
 2  set<K extends keyof Reg & string>(key: K, value: Reg[K]): boolean {
 3    const fullKey = this.k(key);
 4    const payload = JSON.stringify(value);
 5    try {
 6      if (this.storage) this.storage.setItem(fullKey, payload);
 7      else this.fallback?.set(fullKey, payload);
 8      if (this.sameTabEvent) window.dispatchEvent(new CustomEvent(this.sameTabEvent, { detail: { key: fullKey } }));
 9      return true;
10    } catch (err) {
11      console.warn("TypedStorage.set primary failed, trying fallback", err);
12      try {
13        if (this.fallback) {
14          this.fallback.set(fullKey, payload);
15          return true;
16        }
17        return false;
18      } catch (e) {
19        console.error("TypedStorage.set fallback failed", e);
20        return false;
21      }
22    }
23  }
  • set 方法在指定的鍵下儲存一個值,並回傳布林值以表示是否成功。
1  // Set with TTL convenience
2  setWithTTL<K extends keyof Reg & string>(key: K, value: Reg[K], ttlMs?: number): boolean {
3    const payload = { value, expiresAt: ttlMs ? Date.now() + ttlMs : null };
4    return this.set(key, payload as unknown as Reg[K]);
5  }
  • setWithTTL 方法儲存具有 TTL(有效期限)的值。
1  remove<K extends keyof Reg & string>(key: K) {
2    const fullKey = this.k(key);
3    try {
4      if (this.storage) this.storage.removeItem(fullKey);
5      this.fallback?.delete(fullKey);
6    } catch (err) { console.warn("TypedStorage.remove error", err); }
7  }
  • remove 方法會從主要儲存與後備儲存中刪除指定鍵的值。
1  clear() {
2    try {
3      if (this.storage) this.storage.clear();
4      this.fallback?.clear();
5    } catch (err) { console.warn("TypedStorage.clear error", err); }
6  }
7}
  • clear 方法會刪除主要儲存與後備儲存中的所有資料。
 1// Usage example
 2type MyReg = {
 3  theme: "light" | "dark";
 4  user: { id: number; name: string };
 5  draft: string;
 6};
 7
 8const memFallback = new Map<string, string>();
 9const store = new TypedStorage<MyReg>({} as MyReg, {
10  prefix: "myapp:v1",
11  sameTabEvent: "storage:changed",
12  fallback: memFallback
13});
14store.set("theme", "dark");
15console.log(store.get("theme")); // "dark"
16store.setWithTTL("draft", "in-progress...", 1000 * 60 * 60); // keep 1 hour
  • 這段程式碼是使用 TypedStorage 的範例,它在型別安全的鍵值儲存中儲存與讀取例如 "theme""draft" 等值,並同時支援 TTL 與後備機制。它設定了同分頁通知與記憶體內後備,以安全地執行儲存操作。

  • TypedStorage 類別是一個實用的起點。視需要實作 LRU 策略、加密、壓縮,以及後備至 IndexedDB。

總結

使用 TypeScript 搭配 Web Storage 時,請牢記四點:型別安全、對例外的韌性、安全性與同步(多分頁),以達到健壯的設計。我們至今看到的包裝與工具即是這些原則的實例。也可視需要遷移到 IndexedDB 等其他瀏覽器儲存。

您可以在我們的 YouTube 頻道上使用 Visual Studio Code 來跟隨上述文章一起學習。 請也查看我們的 YouTube 頻道。

YouTube Video