← Back to TypeScript Course | Chapter 12: TypeScript with DOM | Lesson 6 of 6

LocalStorage with Types

localStorage stores values as strings, while TypeScript applications often work with numbers, objects, and arrays. Typed helper functions and validation can make localStorage access safer.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.