javascript - 打字稿打字没有按预期工作,我该如何解决?
问题描述
我是一个新手打字稿开发人员,我正在开发一个项目,我将有一个上下文 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
解决方案
在 L21 上,您将类型设置reducer
为Reducer<State, Action>
。您分配给它的实际减速器是不同类型的。虽然尝试缩小传递给 Reducer 的特定性似乎很有帮助,但在实践中这是无法执行的:Redux 将为每个操作运行每个 reducer。
您可以import { AnyAction } from 'redux';
将其用于操作类型,并state
通过推理设置 的值。
推荐阅读
- ruby-on-rails - Rails 5.2.0 关联在 RSpec 中有效,在 Rails 控制台中无效
- python - 在 ipython 会话中设置自定义选项
- nix - 将机密传递给 NixOps 逻辑网络规范
- angularjs - 量角器 URL 未打开,但测试正在通过命令提示符运行
- swift - Swift 中的“SKTexture:加载图像资源时出错”,Xcode 版本 9.4.1
- c# - 选择查询类型以使用 Linq 将其转换为子类型
- html - 视频自动播放不适用于所有 iphone
- python - 从文本文件中的数据制作数据框
- ios - 我怎样才能使这个 UIBarButtonItem Bold?
- powershell - Google SpreadSheet API 和 Powershell - 转换为 CSV