Typed LocalStorage JSON Wrapper

Persist typed preferences through localStorage with an unknown-narrowing guard so corrupted JSON or wrong shapes fall back to defaults.

TypescriptConfig Management

Code

typescriptsnippet
48 lines
// Typed localStorage JSON wrapper: JSON.parse output is unknown until narrowed
interface Preferences {
  theme: "dark" | "light";
  itemsPerPage: number;
}

const KEY = "reader-preferences";
const DEFAULTS: Preferences = { theme: "dark", itemsPerPage: 20 };

// Stored JSON is untrusted: narrow unknown into Preferences before using it
function isPreferences(value: unknown): value is Preferences {
  if (typeof value !== "object" || value === null) return false;
  const candidate = value as Record<string, unknown>;
  return (
    (candidate.theme === "dark" || candidate.theme === "light") &&
    typeof candidate.itemsPerPage === "number" &&
    Number.isInteger(candidate.itemsPerPage) &&
    candidate.itemsPerPage > 0
  );
}

function loadPreferences(storage: Storage): Preferences {
  try {
    const raw = storage.getItem(KEY);
    if (raw === null) return DEFAULTS;
    const parsed: unknown = JSON.parse(raw);
    return isPreferences(parsed) ? parsed : DEFAULTS;
  } catch {
    return DEFAULTS; // corrupted JSON falls back to defaults
  }
}

function savePreferences(storage: Storage, prefs: Preferences): void {
  storage.setItem(KEY, JSON.stringify(prefs));
}

if (typeof localStorage === "undefined") {
  console.log("localStorage unavailable here; the wrapper stays browser-only");
} else {
  savePreferences(localStorage, { theme: "dark", itemsPerPage: 50 });
  console.log("loaded:", loadPreferences(localStorage));

  localStorage.setItem(KEY, '{"itemsPerPage": -5}'); // fails the guard
  console.log("invalid shape ->", loadPreferences(localStorage));

  localStorage.setItem(KEY, "not json at all"); // fails JSON.parse
  console.log("corrupt json ->", loadPreferences(localStorage));
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

localStorage unavailable here; the wrapper stays browser-only

The code in one pass

Typed LocalStorage JSON Wrapper keeps everything in the functions isPreferences, loadPreferences and savePreferences.

What to watch for

  • Nothing must be added to the project before running it.
  • This is browser-side code — localStorage will not resolve in Node.
  • The guard typeof value !== "object" || value === null stops the flow early via a return when its condition holds.

Putting it to use

The primary function signature: function isPreferences(value: unknown)

The run emits 3 labeled sections — loaded:, invalid shape ->, corrupt json -> — one per step.

Core lines

if (typeof value !== "object" || value === null) return false;
return DEFAULTS; // corrupted JSON falls back to defaults
}
return isPreferences(parsed) ? parsed : DEFAULTS;

Interactive Tools for This Topic

FAQ

Does Typed LocalStorage JSON Wrapper run in plain Node.js?
No — it touches `localStorage`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.