atlassian/react-sweet-state

Possibly incorrect type definition for `ActionThunk`

TimeRaider opened this issue · 2 comments

Problem

ActionThunk type definition is incorrect/incompatible (?)

Steps to reproduce:

https://codesandbox.io/s/react-sweet-state-actionthunk-type-error-gz4xrt

  1. Create a simple react-sweet-state store factory that exposes an action to run an async function:
import { Action, createHook, createStore } from "react-sweet-state";

export const createUseService = <T extends (...args: any[]) => any>(
  service: T
) => {
  type State = {};

  const actions = {
    run: (
      ...args: Parameters<T>
    ): Action<
      State,
      void,
      Promise<Awaited<ReturnType<T>>>
    > => async (): Promise<Awaited<ReturnType<T>>> => service(...args)
  };

  const store = createStore<State, typeof actions>({
    initialState: {},
    actions
  });

  return createHook(store);
};
  1. Get typescript error:
Type '{ run: (...args: Parameters<T>) => Action<State, void, Promise<Awaited<ReturnType<T>>>>; }' does not satisfy the constraint 'Record<string, ActionThunk<State, { run: (...args: Parameters<T>) => Action<State, void, Promise<Awaited<ReturnType<T>>>>; }>>'.
  Property 'run' is incompatible with index signature.
    Type '(...args: Parameters<T>) => Action<State, void, Promise<Awaited<ReturnType<T>>>>' is not assignable to type 'ActionThunk<State, { run: (...args: Parameters<T>) => Action<State, void, Promise<Awaited<ReturnType<T>>>>; }>'.
      Types of parameters 'args' and 'args' are incompatible.
        Type 'any[]' is not assignable to type 'Parameters<T>'.ts(2344)

Expected

No TypeScript error

To be honest, I was thinking about deprecating Action as it has some shortcomings compared to:

const actions = {
    run: (...args: Parameters<T>) => async ({ setState }: StoreActionApi<State>) => service(...args)
};

But if #174 improves it without side effects, happy to get that in

@albertogasparin #174 fixed for me yeah (I'm using patch-package in my repo for this)

Regarding your suggestion to use StoreActionApi: createStore requires 2 type arguments, the second of which is usually typeof actions, so removing type annotation Action<State, void, Promise<Awaited<ReturnType<T>>>> from run doesn't help, since the definition of ActionThunk is actually used inside the createStore, so i end up with the same error