type Rect = { x: number; y: number; width: number; height: number }; type Role = "main" | "settings" | "inspector" | "note"; type Persisted = { bounds: Partial>; open: Role[]; }; const ROLES: Role[] = ["main", "settings", "inspector", "note"]; function sanitizeRect(value: unknown): Rect | null { if (typeof value !== "object" || value === null) return null; const { x, y, width, height } = value as Record; if ( typeof x !== "number" || typeof y !== "number" || typeof width !== "number" || typeof height !== "number" || !Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(width) || !Number.isFinite(height) || width < 200 || height < 150 ) { return null; } return { x, y, width, height }; } function parseState(raw: unknown): Persisted { if (typeof raw !== "object" || raw === null) return { bounds: {}, open: [] }; const bounds: Partial> = {}; const rawBounds = (raw as { bounds?: unknown }).bounds; if (typeof rawBounds === "object" && rawBounds !== null) { for (const role of ROLES) { const rect = sanitizeRect((rawBounds as Record)[role]); if (rect) bounds[role] = rect; } } const rawOpen = (raw as { open?: unknown }).open; const open = Array.isArray(rawOpen) ? [ ...new Set( rawOpen.filter((role): role is Role => ROLES.includes(role as Role)), ), ] : []; return { bounds, open }; } function serialize(state: Persisted): string { return `${JSON.stringify(state, null, 2)}\n`; } const parsed = parseState({ bounds: { main: { x: 40, y: 50, width: 1100, height: 780 }, note: { x: "bad", y: 10, width: 400, height: 300 }, settings: { x: 1, y: 2, width: 100, height: 100 }, }, open: ["note", "settings", "bogus", "note"], }); const fallback = parseState("not-an-object"); const roundTrip = parseState(JSON.parse(serialize(parsed))); console.log( JSON.stringify({ evt: "smoke", ok: parsed.bounds.main?.width === 1100 && parsed.bounds.note === undefined && parsed.bounds.settings === undefined && parsed.open.join(",") === "note,settings" && fallback.open.length === 0 && JSON.stringify(roundTrip) === JSON.stringify(parsed), parsed, fallback, roundTrip, }), );