astoilkov / use-local-storage-state

React hook that persists data in localStorage
MIT License
1.09k stars 39 forks source link

Returned value should be unknown type #32

Closed chrbala closed 2 years ago

chrbala commented 2 years ago

The value in [value, setValue] = useLocalStorageState('key') can be updated outside of the closure: dev tools, different app versions, different parts of the app with the same key, etc. To avoid runtime errors, value should therefore be typed as unknown so that assertions (or coercions) are explicitly made before treating the output type the same as the input type.

astoilkov commented 2 years ago

I agree. I've made the change. Thanks for the idea!

chrbala commented 2 years ago

It looks like the change typed it as [unknown, UpdateState<unknown>], but actually it's valid to type it as [unknown, UpdateState<T>]. That will enforce the types going in to the state, but will not guarantee the types coming out.

astoilkov commented 2 years ago

Hmm. But you don't know the types going into the state. My understanding is that there isn't a practical difference between UpdateState<unknown> and UpdateState<T> because of the other overrides that capture the other cases where we know the type. Am I wrong? Can you show an example where there is a difference?

chrbala commented 2 years ago

Ah, looks like you're right, I missed that. Thanks!