TypeScript for atom with setter whose update type is different than the value type #1024
-
I have two
It seems like I had to combine both Here are some of the other solutions I tried that didn't work. When I tried it without types:
... I got this error: When I tried it with just
... I got an error on the When I tried it with just
... I got an error on the I know that I could also use a separate base atom and a derived atom (which works without having to specify types):
... but I was hoping to find a simple way to get it to work using just a single atom. Note: All of the versions listed above are also in the demo. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
This is sort of typescript limitation, and that's why we don't provide such examples in our docs. |
Beta Was this translation helpful? Give feedback.
-
This is mindblowing, I didn't know that you can const lightTheme = { backgroundColor: "#ffffff" };
const darkTheme = { backgroundColor: "#303030" };
type Theme = typeof lightTheme;
type LightOrDark = "light" | "dark";
const themeAtom: WritableAtom<Theme, LightOrDark | Theme> = atom(
lightTheme,
(_get, set, arg) => {
if (arg === 'light') {
set( themeAtom, lightTheme);
}
if (arg === 'dark') {
set(themeAtom, darkTheme);
}
}
); |
Beta Was this translation helpful? Give feedback.
This is sort of typescript limitation, and that's why we don't provide such examples in our docs.
In JS, it's valid. And, in TS, your solution is fine too.
Our current recommendation is to use two atoms, or use
atomWithReducer
(implemented withany
).