Typed History State For SPA Routes
Route single-page apps with typed history state: pushState stores a typed payload, and popstate reads it back with a null guard.
Code
type RouteState = { page: 'home' | 'settings'; userId?: string };
function navigate(state: RouteState, url: string): void {
// 状态对象与 URL 一同写入历史栈(route 语义)
history.pushState(state, '', url);
}
window.addEventListener('popstate', (event: PopStateEvent) => {
const state = event.state as RouteState | null;
console.log('route:', state ? state.page : 'unknown');
});
navigate({ page: 'home' }, '/');
navigate({ page: 'settings', userId: 'u_7' }, '/settings/u_7');
console.log('current page:', (history.state as RouteState).page);What the code does
Everything happens inside the function navigate.
Watch out for
windowexist only in browsers — a Node runtime has no shims for them out of the box.
Applying it
The main signature reads function navigate(state: RouteState, url: string)
The demo output is labeled (route:, current page:), so each line of output maps back to the operation it came from.
Statements that matter
window.addEventListener('popstate', (event: PopStateEvent) => {
const state = event.state as RouteState | null;
console.log('route:', state ? state.page : 'unknown');
});
Interactive Tools for This Topic
FAQ
- Does Typed History State For SPA Routes run in plain Node.js?
- No — it touches `window`, 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.