[Question] [TypeScript] Best way to decouple set() function
See original GitHub issueHello! I wish to be able to dispatch a function instead of using setters and getters. But how is it better to deal with its type?
interface MyStore {
bears: number;
honey: number;
dispatch: (fn: HandlerFn | Partial<MyStore>) => void;
}
// Expected dispatch handler type to be something like:
type HandlerFn = (state: MyStore) => Partial<MyStore>;
export const useStore = create<MyStore>((set) => ({
bears: 1,
honey: 3,
dispatch: (fn: HandlerFn | Partial<MyStore>) => set(fn)
}));
export const incBears = (state: MyStore) => ({
bears: state.bears + 1,
honey: state.honey + 3
});
export const incJustHoney = (state: MyStore) => ({
honey: state.honey + 1
});
export const lotsOfBears = { bears: 999 };
example usage <button onClick={() => dispatch(incBears)}>
.
I expect my handler type to be as HandlerFn
to return Partial
store (or just Partial
store in case of an object).
However Partial
doesn’t match with the set
interface (also I tried to compose anything nice out of zustand types)
The error is:
(parameter) fn: HandlerFn
Argument of type 'HandlerFn' is not assignable to parameter of type 'PartialState<MyStore, keyof MyStore, keyof MyStore, keyof MyStore, keyof MyStore>'.
Type 'HandlerFn' is not assignable to type '(state: MyStore) => MyStore | Pick<MyStore, keyof MyStore>'.
Type 'Partial<MyStore>' is not assignable to type 'MyStore | Pick<MyStore, keyof MyStore>'.
Type 'Partial<MyStore>' is not assignable to type 'Pick<MyStore, keyof MyStore>'.
Types of property 'bears' are incompatible.
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2345)
Basically, if I just want to proxy the set
function, what would be the best way to annotate handler function?
I think I could have specified the handler types as for example (state: MyStore) => Pick<MyStore, "bears", "honey">
, however, I don’t always know which keys my function return
See full example here https://codesandbox.io/s/hopeful-cohen-xy33j?file=/src/store.ts
Issue Analytics
- State:
- Created 2 years ago
- Comments:14 (9 by maintainers)
I think I like
exactOptionalPropertyTypes
. I will try enabling it in zustand/jotai/valtio.Yep it’s already solved with the #662.