atlassian / react-sweet-state

Shared state management solution for React
https://atlassian.github.io/react-sweet-state/
MIT License
871 stars 55 forks source link

Possibly incorrect type definition for `ActionThunk` #173

Closed TimeRaider closed 2 years ago

TimeRaider commented 2 years ago

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 ): Action< State, void, Promise<Awaited<ReturnType>>

=> async (): Promise<Awaited<ReturnType>> => service(...args) };

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

return createHook(store); };


2. Get typescript error:

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



# Expected
No TypeScript error
albertogasparin commented 2 years ago

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

TimeRaider commented 2 years ago

@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