immerjs / use-immer

Use immer to drive state with a React hooks
MIT License
4.04k stars 92 forks source link

Type Definitons: React.useState can be initialized by factory function while useImmer can not #27

Closed gnaeus closed 5 years ago

gnaeus commented 5 years ago

Since useImmer() is a tiny wrapper around native useState() it's initial value can be defined by factory function:

const [state] = useImmer(() => ({
  foo: 123
}));

But inferred type of state is () => { foo: number; } instead of { foo: number; }.
Because signature of React.useState() has overloading for this case:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

While useImmer() signature accepts only raw state object:

function useImmer<S = any>(initialValue: S ): [S, (f: (draft: Draft<S>) => void | S) => void];
mweststrate commented 5 years ago

PR welcome

Op do 18 jul. 2019 17:13 schreef Dmitry Panyushkin <notifications@github.com

:

Since useImmer() is a tiny wrapper around native useState() it's initial value can be defined by factory function:

const [state] = useImmer(() => ({ foo: 123 }));

But inferred type of state is () => { foo: number; } instead of { foo: number; }. Because signature of React.useState() has overloading for this case:

function useState(initialState: S | (() => S)): [S, Dispatch<SetStateAction>];

While useImmer() signature accepts only raw state object:

function useImmer<S = any>(initialValue: S ): [S, (f: (draft: Draft) => void | S) => void];

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/immerjs/use-immer/issues/27?email_source=notifications&email_token=AAN4NBHX6GOUFIYLDE3VDK3QACCBNA5CNFSM4IE4WTAKYY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4HABAT3A, or mute the thread https://github.com/notifications/unsubscribe-auth/AAN4NBFRLRX6YJUHRKJH4UDQACCBNANCNFSM4IE4WTAA .