我有以下减速器代码:
import { IState } from "./initialState";
import { TAction } from "./actions";
import * as types from './types';
const reducer = (state: IState, action: TAction): IState => {
const { type, payload } = action;
switch (type) {
case types.API_REQUEST:
return {
...state,
loading: true
};
case types.API_SUCCESS:
return {
...state,
loading: false,
data: payload
};
case types.API_ERROR:
return {
...state,
error: payload
};
default:
return state;
}
};
export default reducer;
在组件中的使用:
import * as React from "react";
import { useReducer } from "react";
import Context from './newsContext';
import reducer from "./store/reducer";
import initialState from "./store/initialState";
function News(): JSX.Element {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Context.Provider value={{ state, dispatch }}>
<h1>Hello World</h1>
</Context.Provider>);
}
上下文:
import initialState, { IState } from "./store/initialState";
import { TAction } from "./store/actions";
import { createContext, Dispatch } from "react";
interface IContextProps {
state: IState,
dispatch: Dispatch<TAction>;
}
const Context = createContext<IContextProps>({
dispatch: () => {
// Dispatch initial value
},
state: initialState
});
export default Context;
我的编译器显示 ts 错误:
TypeScript error in reactor-ts/src/news/News.tsx(7,42):
No overload matches this call.
Overload 1 of 5, '(reducer: ReducerWithoutAction<any>, initializerArg: any, initializer?: undefined): [any, DispatchWithoutAction]', gave the following error.
Argument of type '(state: IState, action: TAction) => IState' is not assignable to parameter of type 'ReducerWithoutAction<any>'.
Overload 2 of 5, '(reducer: Reducer<any, any>, initialState: any, initializer?: undefined): [any, Dispatch<any>]', gave the following error.
Argument of type '(state: IState, action: TAction) => IState' is not assignable to parameter of type 'Reducer<any, any>'.
Types of parameters 'action' and 'action' are incompatible.
Type 'any' is not assignable to type 'never'.
The intersection 'TAction' was reduced to 'never' because property 'type' has conflicting types in some constituents. TS2769
知道我遗漏了什么 - 为什么编译器失败?
答案 0 :(得分:1)
发现问题 - 哇,从编译器错误中很难理解。
我的代码是:
export type TAction = IApiRequest & IApiSuccess & IApiError;
但必须是:
export type TAction = IApiRequest | IApiSuccess | IApiError;
请求可以是其中一种类型,而不是全部。