To use LocalStorage in TypeScript, you need to create a class that wraps the native LocalStorage API. Here is an example of a LocalStorage class that uses generics to store values of any type:
index.ts540 chars25 lines
In this example, the LocalStorage class takes a type parameter T
which specifies the type of values that will be stored in the LocalStorage.
The constructor
method takes a parameter storageType
that specifies whether to use localStorage
or sessionStorage
.
The setItem
method takes a key
and a value
of type T
, serializes the value to JSON, and stores it in the LocalStorage.
The getItem
method takes a key
and returns the value associated with that key, deserializing it from JSON and returning it as the specified type T
.
The removeItem
method takes a key
and removes the corresponding item from the LocalStorage.
The clear
method clears all items from the LocalStorage.
To use the LocalStorage class, you can create an instance of it and call its methods:
index.ts233 chars6 lines
gistlibby LogSnag