为什么得到“ TS2345:类型为'IInitialState'的参数不能分配给类型为'从不'的参数。”在打字稿中?

时间:2019-11-06 10:52:31

标签: typescript

我正在学习打字稿,并且遇到很多错误。

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>
  );
};

1 个答案:

答案 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。那好吧。希望能有所帮助;祝你好运!

Link to code