Raathigesh / retoggle

🎨 UI controls as React Hooks to control your component state from outside
https://retoggle.netlify.com/
MIT License
1.38k stars 27 forks source link

Add const assertions to hook returns to tighten types #25

Closed hasparus closed 5 years ago

hasparus commented 5 years ago

Hi! I wanted to say I really like retoggle! It's super useful! I've encountered one problem though.

Problem

Repro -- line 64 -- https://codesandbox.io/s/naughty-sammet-k8fcj

Cannot invoke an expression whose type lacks a call signature. Type 'boolean | Dispatch<SetStateAction<boolean>>' has no compatible call signatures.ts(2349)

Inferring hook return types as arrays renders setState functions (second element of returned array) unusable without a type cast.

Solution

We should tell TypeScript we return pairs of kind (state, setState). It's pretty easy and concise to do this with the const assertion and additional effect of it -- making the returned value readonly -- is pretty cool too, because mutating useState state doesn't really work.

I had to update TS and babel though, because it's TS3.4 syntax 😔

Alternative solution

Here's the alternative solution if you didn't like const assertions.

  return [value, setValue] as [number, React.Dispatch<React.SetStateAction<number>>];

➕ Wouldn't have to update babel and TS. ➖ Pretty terrible to look at 😅

Raathigesh commented 5 years ago

Thank you for the PR. looks good to me.

Raathigesh commented 5 years ago

Released - https://github.com/Raathigesh/retoggle/releases/tag/0.4.0