LocalStorage with Types
In this page:
Storing Strings
localStorage.setItem and getItem only ever work with strings, so storing a string value is the simplest case and needs no extra type conversion on either side.
Example: Storing Strings
localStorage.setItem("username", "Ravi");
const name: string | null = localStorage.getItem("username");
console.log(name);
Storing Numbers
Storing a number means converting it to a string before saving (String(value)) and parsing it back with Number() on retrieval, since localStorage has no concept of a numeric type at all.
Example: Storing Numbers
localStorage.setItem("age", String(25));
const age: number = Number(localStorage.getItem("age"));
console.log(age);
Storing Objects with JSON
Storing an object means serializing it to a JSON string with JSON.stringify before saving and parsing it back with JSON.parse, which returns any by default unless you explicitly annotate or assert the expected shape.
Example: Storing Objects with JSON
interface User { name: string; age: number }
const user: User = { name: "Ravi", age: 25 };
localStorage.setItem("user", JSON.stringify(user));
const loaded: User = JSON.parse(localStorage.getItem("user")!);
console.log(loaded.name);
Typed LocalStorage Helpers
A typed localStorage helper wraps setItem/getItem in generic functions that handle the JSON conversion internally, so the rest of your code can read and write typed values without repeating boilerplate at every call site.
Example: Typed LocalStorage Helpers
function setTyped<T>(key: string, value: T): void {
localStorage.setItem(key, JSON.stringify(value));
}
function getTyped<T>(key: string): T | null {
const raw = localStorage.getItem(key);
return raw ? (JSON.parse(raw) as T) : null;
}
setTyped("count", 5);
console.log(getTyped<number>("count"));
Safe Parsing and Validation
Because JSON.parse returns any, safe parsing means validating the shape of whatever comes back — checking required fields exist and have the right type — before trusting it as your expected type, since stored data could be stale or tampered with.
Example: Safe Parsing and Validation
interface User { name: string }
function isUser(value: any): value is User {
return typeof value?.name === "string";
}
localStorage.setItem("user", JSON.stringify({ name: "Ravi" }));
const parsed = JSON.parse(localStorage.getItem("user")!);
if (isUser(parsed)) console.log(parsed.name);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: