store generic into localstorage in typescript

To save a generic type to LocalStorage in TypeScript, you can serialize the object to a JSON string and then save it to LocalStorage using the setItem() method. Here's an example:

index.ts
function saveToLocalStorage<T>(key: string, item: T): void {
  const itemJson = JSON.stringify(item);
  localStorage.setItem(key, itemJson);
}
143 chars
5 lines

In this example, the saveToLocalStorage() function takes two arguments: a key to identify the item in LocalStorage, and the item itself. The item parameter is of type T, which means it can be any type, including a custom type you've defined.

Inside the function, the JSON.stringify() method is used to serialize the item to a JSON string. This is necessary because LocalStorage can only store strings.

Finally, the setItem() method is called on the localStorage object to save the JSON string to LocalStorage under the specified key.

To retrieve the item from LocalStorage, you can use the getItem() method to retrieve the JSON string, and then parse it back into an object using the JSON.parse() method:

index.ts
function getFromLocalStorage<T>(key: string): T | null {
  const itemJson = localStorage.getItem(key);
  if (!itemJson) return null;
  const item = JSON.parse(itemJson);
  return item as T;
}
192 chars
7 lines

In this example, the getFromLocalStorage() function takes a key parameter to identify the item in LocalStorage. It returns an object of type T or null.

Inside the function, the getItem() method is called on the localStorage object to retrieve the JSON string that was saved under the specified key. If no item is found, the function returns null.

If an item is found, the JSON.parse() method is used to parse the JSON string back into an object. The as T syntax is used to tell TypeScript that the parsed object should be cast to type T.

With these functions, you can easily save and retrieve generic types from LocalStorage in TypeScript.

gistlibby LogSnag