首页 > 解决方案 > 打字稿打字没有按预期工作,我该如何解决?

问题描述

我是一个新手打字稿开发人员,我正在开发一个项目,我将有一个上下文 API 来管理我的状态。

我已经尝试了很多方案来解决减速器问题,但我做不到,感谢任何帮助。

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

操场

标签: javascriptreactjstypescriptautocompletereact-context

解决方案


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

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


推荐阅读