Replies: 6 comments 9 replies
-
|
Very interesting: https://tsplay.dev/mq5Jqm @devanshj thoughts? |
Beta Was this translation helpful? Give feedback.
-
|
As noted in https://github.com/pmndrs/zustand/blob/main/docs/typescript.md:
But if a function doesn't have input arguments, then typescript can infer The second solution (for ES5) is even better and shorter and technically not a hack, as we are giving TS a hint about our type. I wish it would work for ESNext target too. I guess it's related to different hoisting rules between es5 and es6. |
Beta Was this translation helpful? Give feedback.
-
|
Here is a revised version: https://tsplay.dev/N9167N It removes the need for function, as it might be confusing, and requires only a single type cast. |
Beta Was this translation helpful? Give feedback.
-
|
Hey @dhmk083, I just published a package that allows to infer the type of the store. The approach is quite similar to yours, but not exactly the same. Take a look if you're interested - https://github.com/shfrmn/zustand-types |
Beta Was this translation helpful? Give feedback.
-
|
Yes, it's good, but it doesn't take into account any middleware. For example, if store looks like this: import { immer } from 'zustand/middleware/immer'
function MyStore(set: SetState<typeof MyStore>) {
...
}
export const useStore = create(immer(MyStore))Then your types won't be able to see that |
Beta Was this translation helpful? Give feedback.
-
|
@dhmk083 how to set types with your solution? I tried const useStore = create(function () {
const [set, get, api] = getParams<typeof useStore>(arguments);
return {
id: undefined as number | undefined,
name: undefined as string | undefined,
...
};
}); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Not really an issue, just a suggestion.
I found a way to let typescript to infer store type. It just needs some hacking, but it's quite short and also works better than
combinemiddleware.Here's the demo (also codesandbox):
So, the idea is to omit
set, get, apiparameters from function to break circular type dependency. It lets typescript to infer store type by return value only.And if you have
"target": "es5"in your tsconfig.json, then it's even simpler:Unfortunately, it doesn't work with any other targets, only with
es5.Beta Was this translation helpful? Give feedback.
All reactions