我正在学习打字稿,并且遇到很多错误。
在useReducer
钩子上,出现以下TS错误:
TS2345:“ IInitialState”类型的参数不能分配给“ never”类型的参数。
我的代码是:
...
interface IMovie {
Poster: string;
Title: string;
Year: string;
}
interface IInitialState {
loading: boolean;
movies: IMovie[];
errorMessage: string | null
}
interface IAction {
type: string;
payload?: any,
error?: string
}
const initialState: IInitialState = {
loading: true,
movies: [],
errorMessage: null
};
const reducer = (state: IInitialState, action: IAction) => {
switch (action.type) {
case 'SEARCH_MOVIE_REQUEST':
return {
...state,
loading: true,
errorMessage: null
};
case 'SEARCH_MOVIE_SUCCESS':
return {
...state,
loading: false,
movies: action.payload
};
case 'SEARCH_MOVIE_FAILURE':
return {
...state,
loading: false,
errorMessage: action.error
};
default:
return state;
}
};
const App: React.FC = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div className="App">
...
</div>
);
};
答案 0 :(得分:0)
我认为您的问题是reducer
并不是有效的reducer,因为其返回类型不能完全分配给IInitialState
。它是 close ,但距离React的类型定义还差得远。
如果您尝试检查返回的内容,则会看到其类型
{
loading: boolean;
movies: any;
errorMessage: string | null;
} | {
loading: boolean;
errorMessage: string | undefined;
movies: IMovie[];
}
问题在于第二个并集元素将errorMessage
作为string | undefined
,而不是根据需要的string | null
。看起来您的SEARCH_MOVIE_FAILURE
案例返回了action.error
,而不是string | undefined
类型的string | null
。您可能需要将其更改为以下内容:
case 'SEARCH_MOVIE_FAILURE':
return {
...state,
loading: false,
errorMessage: action.error || null // here
};
我想那应该可以解决您的问题。不幸的是,您收到的错误消息太不透明了。问题出在reducer
,而不是initialState
。那好吧。希望能有所帮助;祝你好运!