Introduction
localStorage and sessionStorage encapsulate set, get, remove, clear and other methods for convenient use.
setSet valuegetGet valueremoveDelete valueclearClear values
⚠️ Ensure type-safe key access
- The generic
Tpassed tolocalextendsLocal - The generic
Tpassed tosessionextendsSession LocalandSessionare defined insrc/types/global.d.ts
Usage Example
Add custom types to Local and Session in src/types/global.d.ts
ts
/** LocalStorage */
interface Local {
// Existing types ...
localMsg: string;
}
/** SessionStorage */
interface Session {
// Existing types ...
sessionMsg: string;
}LocalStorage
ts
import { local } from "@/utils";
/**
* Incorrect usage
* - The parameter "msg" cannot be assigned to a parameter of type "keyof Local"
*/
local.set("msg", "hello World");
/**
* Correct usage
*/
local.set("localMsg", "hello VitePress");
local.get("localMsg");
local.remove("localMsg");
local.clear();SessionStorage
ts
import { session } from "@/utils";
/**
* Incorrect usage
* - The parameter "msg" cannot be assigned to a parameter of type "keyof Session"
*/
session.set("msg", "hello World");
/**
* Correct usage
*/
session.set("sessionMsg", "hello VitePress");
session.get("sessionMsg");
session.remove("sessionMsg");
session.clear();
nuyoah