dscheerens / ngx-webstorage-service

Module for Angular that provides service wrappers for the Web Storage API
MIT License
65 stars 11 forks source link

TS typings #43

Open Granaat opened 2 years ago

Granaat commented 2 years ago

If you define StorageService<T>, shouldn't get() be get<K extends keyof T>(key: K) instead of get(key: string): T ? Because now, when you get a key, it returns the entire object type.

dscheerens commented 2 years ago

Because now, when you get a key, it returns the entire object type.

That is actually by design :)

Basically it reads and writes whatever you put in the web storage:

storageService.put('myData', { greeting: 'Hi!', happy: true });

storageService.get('myData'); // returns { greeting: 'Hi!', happy: true }

The type parameter T allows you to be more specific about what type of data you're reading and writing. Where the transcoder will do the encoding/decoding.

Granaat commented 2 years ago

But having these, no transcoder usage is needed: with i.e. @Inject(LOCAL_STORAGE) private storageService: StorageService<ILocalStorage>

has<K extends keyof T>(key: K): boolean;
get<K extends keyof T>(key: K): T[K] | undefined;
set<K extends keyof T>(key: K, value: T[K]): void;
remove<K extends keyof T>(key: K): void;

In your case, setting StorageService<{ myData: { ... }, secondData: number[] }>, you don't get the correct object. (intellisense / typescript wise). Your storageService.get('myData') would result in:

storageService.get('myData').myData
storageService.get('myData').secondData