用于thunk调度的正确TypeScript类型?

Car*_*pon 8 typescript reactjs redux redux-thunk

我有一个异步redux动作,所以使用thunk中间件.

我有mapStateToProps,mapDispatchToPropsconnect为组件的功能如下:

const mapStateToProps = (store: IApplicationState) => {
  return {
    loading: store.products.loading,
    products: store.products.products
  };
};
const mapDispatchToProps = (dispatch: any) => {
  return {
    getAllProducts: () => dispatch(getAllProducts())
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ProductsPage);
Run Code Online (Sandbox Code Playgroud)

这一切都有效,但我想知道是否有可能替换anydispatch参数中的类型mapDispatchToProps

我试过ThunkDispatch<IApplicationState, void, Action>但在connect函数上遇到以下TypeScript错误:

Argument of type 'typeof ProductsPage' is not assignable to parameter of type 'ComponentType<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>>'.
  Type 'typeof ProductsPage' is not assignable to type 'ComponentClass<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>, any>'.
    Types of property 'getDerivedStateFromProps' are incompatible.
      Type '(props: IProps, state: IState) => { products: IProduct[]; search: string; }' is not assignable to type 'GetDerivedStateFromProps<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>, any>'.
        Types of parameters 'props' and 'nextProps' are incompatible.
          Type 'Readonly<Matching<{ loading: boolean; products: IProduct[]; } & { getAllProducts: () => Promise<void>; }, IProps>>' is not assignable to type 'IProps'.
            Types of property 'getAllProducts' are incompatible.
              Type '() => Promise<void>' is not assignable to type '() => (dispatch: Dispatch<AnyAction>) => Promise<void>'.
                Type 'Promise<void>' is not assignable to type '(dispatch: Dispatch<AnyAction>) => Promise<void>'.
                  Type 'Promise<void>' provides no match for the signature '(dispatch: Dispatch<AnyAction>): Promise<void>'.
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

是否可以替换anydispatch参数中的类型mapDispatchToProps

Luk*_*ela 8

这个设置对我来说非常有效:

// store.ts
//...
export type TAppState = ReturnType<typeof rootReducer>;
export type TDispatch = ThunkDispatch<TAppState, void, AnyAction>;
export type TStore = Store<TAppState, AnyAction> & { dispatch: TDispatch };
export type TGetState = () => TAppState;
//...
const store: TStore = createStore(
  rootReducer,
  composeEnhancers(applyMiddleware(...middleware), ...enhancers)
);
export default store;
Run Code Online (Sandbox Code Playgroud)

我的设置中的位置rootReducer如下所示const rootReducer = createRootReducer(history);

// createRootReducer.ts
import { combineReducers, Reducer, AnyAction } from 'redux';
import { History } from 'history';
import {
  connectRouter,
  RouterState,
  LocationChangeAction,
} from 'connected-react-router';
// ... here imports of reducers
type TAction = AnyAction & LocationChangeAction<any>;

export type TRootReducer = Reducer<
  {
    // ... here types of the reducer data slices
    router: RouterState;
  },
  TAction
>;
const createRootReducer = (history: History): TRootReducer =>
  combineReducers({
    // ... here actual inserting imported reducers
    router: connectRouter(history),
  });

export default createRootReducer;
Run Code Online (Sandbox Code Playgroud)

然后在连接组件中

import { connect } from 'react-redux';
import Add, { IProps } from './Add'; // Component
import { TDispatch, TAppState } from '../../store';

type TStateProps = Pick<
  IProps,
  'title' | 'data' | 'loading'
>;
const mapStateToProps = (
  state: TAppState,
): TStateProps => {
    // ... here you have typed state :)
    // and return the TStateProps object as required
    return {
      loading: state.someReducer.loading,
      //...
    }
}

type TDispatchProps = Pick<IProps,  'onSave'>;
const mapDispatchToProps = (
  dispatch: TDispatch,
): TDispatchProps => {
   // here you  have typed dispatch now
   // return the TDispatchProps object as required
   return {
    onSave: (): void => {
      dispatch(saveEntry()).then(() => {
        backButton();
      });
    },
   }
}

Run Code Online (Sandbox Code Playgroud)

至于 thunk 动作我做如下

// this is a return type of the thunk
type TPromise = Promise<ISaveTaskResponse | Error>;

export const saveEntry = (): ThunkAction<
  TPromise, // thunk return type
  TAppState, // state type
  any, // extra argument, (not used)
  ISaveEntryAction // action type
> => (dispatch: TDispatch, getState: TGetState): TPromise => {
  // use getState
  // dispatch start saveEntry action
  // make async call
  return Axios.post('/some/endpoint', {}, {})
    .then((results: { data: ISaveTaskResponse; }): Promise<ISaveTaskResponse> => {
      // get results
      // you can dispatch finish saveEntry action
      return Promise.resolve(data);
    })
    .catch((error: Error): Promise<Error> => {
      // you can dispatch an error saveEntry action
      return Promise.reject(error);
    });
};

Run Code Online (Sandbox Code Playgroud)


Fyo*_*dor 2

Redux 可以调度普通对象的操作。说我们有这样的行动{type: 'ACTION2'}。我们可以创建动作创建者并将其包装在调度中,如下所示

// This is our action
interface Action2 extends Action { type: "ACTION2"; }

// And this is action crator
const action2 = (): Action2 => ({ type: "ACTION2" });
Run Code Online (Sandbox Code Playgroud)

通过thunk中间件 Redux 可以调度函数。我们可以像这样创建异步操作

// This action will be dispatched from async action creator
interface Action1 extends Action { type: "ACTION1"; payload: string; }

// And async action creator
const thunkAction = (arg: string): ThunkAction<Promise<void>, {}, AppState, KnownActions> => 
    async dispatch => {
        const res = await asyncFunction(arg);
        dispatch({ type: "ACTION1", payload: res });
    },  
Run Code Online (Sandbox Code Playgroud)

这里ThunkAction<R, S, E, A extends Action>使用的是类型。它接受以下类型参数:

  • R保留内部函数的返回类型。在上面的示例中,内部函数是异步函数,因此它返回Promise<void>
  • S停留在应用程序状态
  • E是未使用的扩展属性类型
  • A是动作的类型。KnownActions上面的示例是所有可能的操作类型的并集 ( type KnownActions = Action1 | Action2;)

现在让我们看看如何键入组件。

interface Component1DispatchProps {
  action2: () => Action2;
  thunkAction: (arg: string) => Promise<void>;
}

interface Component1StateProps {
  stateprop: string;
}

const mapDispatchToProps = (
  dispatch: ThunkDispatch<AppState, {}, KnownActions>
) => {
  return {
    action2: () => dispatch(action2()),
    thunkAction: (arg: string) => 
      dispatch(thunkAction(arg))
  };
};
Run Code Online (Sandbox Code Playgroud)

thunkAction方法返回dispatch(thunkAction(arg)),其中thunkAction(arg)返回ThunkAction<Promise<void>, {}, AppState, KnownActions>. 因此dispatch将使用类型参数进行调用ThunkAction,并将解析为

<TReturnType>(
  thunkAction: ThunkAction<TReturnType, TState, TExtraThunkArg, TBasicAction>,
): TReturnType;
Run Code Online (Sandbox Code Playgroud)

在我们的示例中,结果dispatch(thunkAction(arg))将返回TReturnTypeor Promise<void>。这样的签名是为thunkAction中设置的Component1DispatchProps

完整的例子在这里