Generic State Manager
What you'll build
A Store<T> class that holds state of type T, notifies subscribers on change, and only accepts updater functions that return type T.
Goals
- Create a generic state container
- Enforce immutable updates via types
- Type subscription callbacks
- Build a mini Redux-like pattern
Prerequisites
- Generics
- Functions as types
- Immutable patterns
Steps
- 1
Define the Store class
Create a generic Store<T> that holds state and a list of listeners. The state is only readable from outside; updates go through a setter.
Codeclass Store<T> { private state: T; private listeners: ((state: T) => void)[] = []; constructor(initial: T) { this.state = initial; } get(): T { return this.state; } set(updater: (prev: T) => T): void { this.state = updater(this.state); this.listeners.forEach(l => l(this.state)); } subscribe(listener: (state: T) => void): () => void { this.listeners.push(listener); return () => { this.listeners = this.listeners.filter(l => l !== listener); }; } }Expected result
A generic Store class with typed get, set, and subscribe methods.
- 2
Use the store with a typed state
Create a store with a specific state type. All updates and subscriptions are now type-checked.
Codeinterface CounterState { count: number; label: string; } const store = new Store<CounterState>({ count: 0, label: "visits" }); store.subscribe(s => console.log(s.count)); store.set(prev => ({ ...prev, count: prev.count + 1 }));Expected result
State updates are type-safe. Returning a wrong shape is a compile error.
- 3
Add type guards & runtime checks
Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.
Codetype User = { id: number; name: string }; function isUser(value: unknown): value is User { if (typeof value !== "object" || value === null) return false; const obj = value as Record<string, unknown>; return typeof obj.id === "number" && typeof obj.name === "string"; } // Usage with unknown input const data: unknown = JSON.parse(rawJson); if (isUser(data)) { console.log(data.name); // TS knows data is User here } else { console.error("Invalid user data"); }Expected result
When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.
- 4
Add generic utility functions
Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.
Codefunction groupBy<T, K extends string | number>( items: T[], keyFn: (item: T) => K ): Record<K, T[]> { const result = {} as Record<K, T[]>; for (const item of items) { const key = keyFn(item); (result[key] ??= []).push(item); } return result; } // Usage const byAge = groupBy(users, u => u.age);Expected result
groupBy groups any array by key, returning a type-safe Record.
- 5
Compile check & type tests
Run tsc --noEmit to confirm no type errors; use expectTypeOf or @ts-expect-error comments for type-level tests. A clean compile is the acceptance criterion for TypeScript projects.
Code// Run: npx tsc --noEmit // Type-level test with @ts-expect-error // @ts-expect-error — string is not a number const bad: number = "oops"; // Correct usage compiles cleanly const good: number = 42;Expected result
tsc --noEmit produces no errors; the @ts-expect-error line does error (and is suppressed).
Try it yourself
What you learned
You built a type-safe state container. The updater function (prev: T) => T enforces that updates return the same shape as the current state, preventing partial or malformed updates at compile time.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.