immerjs / use-immer

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

Typescript error on Generics Reducer #64

Closed sonatard closed 3 years ago

sonatard commented 4 years ago

This code can execute but it has an error on the reducer.

https://codesandbox.io/s/custom-hook-v7-1-e6yl0b?file=/src/useStack.ts

error log

Removing the generics will remove the error.

https://codesandbox.io/s/custom-hook-v72-forked-51k3h?file=/src/useStack.ts

How can I fix it?

mweststrate commented 3 years ago

The reproduction doesn't seem to reflect the question. For the original problem, passing the generic to immerReducer might help: useImmerReducer<StackState<T>>(stackReducer())

NMinhNguyen commented 2 years ago

Using useImmerReducer<StackState<T>>(stackReducer(), initStack); in the original reproduction still causes an error:

Argument of type '(stack: StackState<T | Draft<T>>, action: StackAction<T | Draft<T>>) => void | StackState<T | Draft<T>>' is not assignable to parameter of type 'Reducer<StackState<T>, any>'.
  Type 'void | StackState<T | Draft<T>>' is not assignable to type 'void | StackState<T>'.
    Type 'StackState<T | Draft<T>>' is not assignable to type 'void | StackState<T>'.
      Type '(T | Draft<T>)[]' is not assignable to type 'StackState<T>'.
        Type 'T | Draft<T>' is not assignable to type 'T'.
          'T' could be instantiated with an arbitrary type which could be unrelated to 'T | Draft<T>'.ts(2345)