Typed LocalStorage JSON Wrapper
Persist typed preferences through localStorage with an unknown-narrowing guard so corrupted JSON or wrong shapes fall back to defaults.
Code
// 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-onlyThe 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 —
localStoragewill not resolve in Node. - The guard
typeof value !== "object" || value === nullstops the flow early via areturnwhen 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
INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.TOML to JSON ConverterParse TOML configuration into JSON, supporting tables, arrays of tables, inline tables, and basic or literal strings.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.