localstorage class in typescript

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.ts
class LocalStorage<T> {
  private storage: Storage;

  constructor(storageType: 'localStorage' | 'sessionStorage') {
    this.storage = window[storageType];
  }

  public setItem(key: string, value: T): void {
    this.storage.setItem(key, JSON.stringify(value));
  }

  public getItem(key: string): T | null {
    const item = this.storage.getItem(key);
    return item ? JSON.parse(item) : null;
  }

  public removeItem(key: string): void {
    this.storage.removeItem(key);
  }

  public clear(): void {
    this.storage.clear();
  }
}
540 chars
25 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.ts
const localStorage = new LocalStorage<string>('localStorage');
localStorage.setItem('myKey', 'myValue');
const myValue = localStorage.getItem('myKey'); // myValue === 'myValue'
localStorage.removeItem('myKey');
localStorage.clear();
233 chars
6 lines

gistlibby LogSnag