Values stored as browser strings can be parsed back into a typed record.

storage record Storage APIs keep string values, so code usually parses JSON before reading typed fields.

Storage JSON Record

visitCount
storage.ts
Replay: real traced execution (multi-file project)
type VisitState = {
    visits: number;
    theme: string;
};

function readState(storage: Record<string, string>): VisitState {
    return JSON.parse(storage.state) as VisitState;
}

const visitCount: number = 3;
const storage: Record<string, string> = {
    state: JSON.stringify({
        visits: visitCount,
        theme: "light"
    })
};
const state: VisitState = readState(storage);

console.log(`${state.theme}:${state.visits + 1}`);
type VisitState = {
    visits: number;
    theme: string;
};

function readState(storage: Record<string, string>): VisitState {
    return JSON.parse(storage.state) as VisitState;
}

const visitCount: number = 7;
const storage: Record<string, string> = {
    state: JSON.stringify({
        visits: visitCount,
        theme: "light"
    })
};
const state: VisitState = readState(storage);

console.log(`${state.theme}:${state.visits + 1}`);
  1. visitCount ← 3, storage ← [object Object]

    7    return JSON.parse(storage.state) as VisitState;8}910const visitCount→ 3: number = 3;  //@visitCount=711const storage→ [object Object]: Record<string, string> = {12    state: JSON.stringify({13        visits: visitCount3,14        theme: "light"15    })16};17const state: VisitState = readState(storage[object Object]);
  2. function readState(storage: Record<string, string>): VisitState

    3    theme: string;4};56function readState(storage[object Object]: Record<string, string>): VisitState {7    return JSON.parse(storage.state{"visits":3,"theme":"light"}) as VisitState;8}
  3. state ← [object Object], state.visits ← 3

    15    })16};17const state→ [object Object]: VisitState = readState(storage[object Object]);1819console.log(`${state.themelight}:${state.visits→ 3 + 1}`);
    outputlight:4
  1. visitCount ← 7, storage ← [object Object]

    7    return JSON.parse(storage.state) as VisitState;8}910const visitCount→ 7: number = 7;11const storage→ [object Object]: Record<string, string> = {12    state: JSON.stringify({13        visits: visitCount7,14        theme: "light"15    })16};17const state: VisitState = readState(storage[object Object]);
  2. function readState(storage: Record<string, string>): VisitState

    3    theme: string;4};56function readState(storage[object Object]: Record<string, string>): VisitState {7    return JSON.parse(storage.state{"visits":7,"theme":"light"}) as VisitState;8}
  3. state ← [object Object], state.visits ← 7

    15    })16};17const state→ [object Object]: VisitState = readState(storage[object Object]);1819console.log(`${state.themelight}:${state.visits→ 7 + 1}`);
    outputlight:8