facebookexperimental / Recoil

Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
https://recoiljs.org/
MIT License
19.6k stars 1.19k forks source link

Typescript - Generic Keys #832

Open mthines opened 3 years ago

mthines commented 3 years ago

Hey guys.

Link to CodeSandbox

I'm using Recoil for our project and so far it's been amazing. I've been trying out different setup in order to create a scalable structure because I predict we're quickly gonna get extremely atoms and selectors.

One thing I'm really missing is being able to pass a string literal as a generic to the atom function, like shown in the atoms/todo.ts#11. That would make it possible for me to prevent typing error that could happen when referring to the same key name multiple places.

I looked at the typing's and did a small local patch, and it didn't look like there were any problems just adding the key's type as a generic?

What's the idea behind the key not being generic?

Short example of the idea

In my setup I need to write the same key 3 times, which then has a big chance for errors.

type AtomKeys = "todo:input" | "todo:list";

const input = atom<string, AtomKeys>({
  key: "todo:input", // This can't be typed to match one of the keys in AtomKeys
  default: "",
  effects_UNSTABLE: [
    persistAtomEffect<string, AtomKeys>("todo:input")
  ]
});

export default {
  "todo:input": input,
};

It looks like it throws an error regarding localStorage not being available in the beginning, but that dissappears.

Thanks for your guys amazing work! ❤️

mthines commented 3 years ago

Reference of the local patch I did, adding Keys as a type extending the NodeKeyand defaulting to NodeKeyso it's not mandatory.

https://github.com/facebookexperimental/Recoil/pull/834