打字稿打字没有按预期工作,我该如何解决这个问题?

typescript typing isn't working as intended, how can I solve this?

我是一个 noob typescript 开发人员,我正在开发一个项目,在该项目中我将有一个上下文 API 来管理我的状态。

我已经尝试了很多方案来解决 reducer 问题,但我不能,任何帮助表示赞赏。

import React, { useReducer } from "react";

type ActionType = { type: string; payload: any };
type StateType = { [key: string]: any };
type Dispatch = (action: ActionType) => void;
type ActionFunc = (dispatch: Dispatch) => Promise<void>;

type Actions<A extends { [key: string]: ActionFunc }> = {
  [key in keyof A]: ReturnType<A[keyof A]>;
};

type Reducer<S extends StateType, A extends ActionType> = (
  state: S,
  action: A
) => {
  [key in keyof S]: any;
};

type InitializeContext<State, Action extends ActionType> = (
  reducer: Reducer<State, Action>,
  actions: { [key: string]: ActionFunc },
  initialState: { [key in keyof State]: keyof State[key] }
) => void;
//---
//Test
//---
type TestAction = {
  type: "@ADD_PRODUCT";
  payload: {
    id: number;
    name: string;
    isCat: boolean;
  };
};

type TestState = { products: Array<TestAction["payload"]> };

const initialState: TestState = {
  products: []
};

const reducer: Reducer<TestState, TestAction> = (state, action) => {
  switch (action.type) {
    case "@ADD_PRODUCT":
      return {
        products: [...state.products, action.payload]
      };
    default:
      return state;
  }
};

const addProduct = (dispatch: Dispatch) => async () => {};

//------
//EndTest
//------
const initializeContext: InitializeContext<StateType, ActionType> = (
  reducer,
  actions,
  initialState
) => {
  const ContextApi = React.createContext({});

  const Provider: React.FC = (props) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const boundActions: Actions<typeof actions> = {};

    for (const key in actions) {
      if (Object.prototype.isPrototypeOf.call(actions, key)) {
        boundActions[key] = actions[key](dispatch);
      }
    }

    return (
      <ContextApi.Provider value={{ state, ...boundActions }}>
        {props.children}
      </ContextApi.Provider>
    );
  };
  // return { ContextApi, Provider }
};

initializeContext(reducer, { addProduct }, initialState); // why Type 'StateType' is not assignable to type 'TestState'

代码框:https://codesandbox.io/s/typescript-playground-export-forked-u8ehp?file=/index.tsx:1922-1981

Playground

在 L21 上,您将 reducer 的类型设置为 Reducer<State, Action>。您分配给它的实际减速器属于不同类型。虽然尝试缩小将传递给 Reducer 的内容的特异性似乎很有帮助,但实际上这将无法执行:Redux 将 运行 每个 reducer 的每个操作。

您可以import { AnyAction } from 'redux';并将其用于操作类型,并通过推理设置state的值。