a generic function for storing cache into localstorage in typescript

Here's an example of a generic function in TypeScript that can be used to store data in the localStorage cache:

index.ts
function setCache<T>(key: string, data: T): void {
  localStorage.setItem(key, JSON.stringify(data));
}
104 chars
4 lines

This function takes two arguments: the key under which to store the data in localStorage and the actual data to be stored. The T in <T> allows for any data type to be passed through, making the function more flexible and reusable.

To use the function, simply call it passing in the desired key and data:

index.ts
const user = { name: 'John', age: 30 };
setCache('user', user);
64 chars
3 lines

This will store the user object in localStorage under the key 'user'.

gistlibby LogSnag