Typescript - using generics to for localstorage
generics, local-storage, typescript
Solution
Safer to cast like this `JSON.parse(data) as T` as you will get null if the cast doesn't work (instead of an exception)
Problem
I'm using the following code set and get strongly typed item with local storage. The set works as expected and puts JSON into local storage. However, when getting the same item out, the casting to the generic type doesn't seem to work. It doesn't cause and exception and just return a JSON string, not the desired typed object. ``` export class StorageService { constructor() { } setItem<T>(key: string, item: T): void { localStorage.setItem(key, JSON.stringify(item)); } getItem<T>(key: string): T { let data: any = localStorage.getItem(key); if (!data) return null; let obj: T; try { obj = <T>JSON.parse(data); } catch (error) { obj = null; } return obj } } ```