I'm currently working on a straightforward Local Storage utility method. My goal is to retrieve an entry based on a key and a specified type.
Here's the implementation:
get<T>(key: string): T {
const data = localStorage.getItem(key);
const object = JSON.parse(data) as T;
if (!object) {
throw new Error(`Unable to cast ${JSON.stringify(data)`);
}
return object;
}
Unfortunately, the casting as T
may not be efficient in all cases.
For example, if my Local Storage entry is <'key', 10>, Then:
get<NoMatterTheClass>('key')
will return 10 as a number without throwing any errors.
My question is: How can I ensure that the cast is always successful? Should I use a generic constraint? I've tried using
<T extends (new() => T)>
but it didn't work as expected.
Thanks for any insights you can provide!