TypeScript CRA с настройкой Redux - PullRequest
0 голосов
/ 10 марта 2020

Я пытаюсь выполнить быструю настройку с работающим приложением Create React и Redux, мне явно чего-то не хватает ...

Index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { store } from './store/store'
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

const rootElement = document.getElementById('root')
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  rootElement
)
serviceWorker.unregister();

store

import { createStore } from "redux";
import { rootReducer } from "../reducers/index";
const store = createStore(rootReducer);
//                           ^ error
export { store };

Я получаю ошибку

No overload matches this call.
  Overload 1 of 2, '(reducer: Reducer<{ articles: never[]; }, UserAction>, enhancer?: StoreEnhancer<unknown, unknown> | undefined): Store<{ articles: never[]; }, UserAction>', gave the following error.
    Argument of type '(state: { articles: never[]; } | undefined, action: UserAction) => { articles: any[]; }' is not assignable to parameter of type 'Reducer<{ articles: never[]; }, UserAction>'.
      Type '{ articles: any[]; }' is not assignable to type '{ articles: never[]; }'.
        Types of property 'articles' are incompatible.
          Type 'any[]' is not assignable to type 'never[]'.
            Type 'any' is not assignable to type 'never'.
  Overload 2 of 2, '(reducer: Reducer<{ articles: never[]; }, UserAction>, preloadedState?: { articles: never[]; } | undefined, enhancer?: StoreEnhancer<unknown, {}> | undefined): Store<{ articles: never[]; }, UserAction>', gave the following error.
    Argument of type '(state: { articles: never[]; } | undefined, action: UserAction) => { articles: any[]; }' is n

и редуктор

const initialState = {
    articles: []
  };

  export interface UserAction {
    type: string;
    payload: any;
}

  const rootReducer = (state = initialState, action: UserAction) => {
    switch (action.type) {
        case 'ADD_ARTICLE': {
          return {
            ...state,
            articles: [action.payload, ...state.articles],
          };
        }
        default:
          return state;
      }
  }

  export { rootReducer };

Приложение

import React from "react";
import { rootReducer } from "./reducers/index";

function App() {
  const addArticle = () => {
    rootReducer({type: 'ADD_ARTICLE', payload: 'my new article'}) // this isnt right!
  };
  return <button onClick={addArticle}>Add Article</button>;
}

export default App;

1 Ответ

1 голос
/ 10 марта 2020

Вот пример вашего редуктора с явными типами:

interface IArticles {
  articles: string[];
}

const initialState: IArticles = {
  articles: []
};

export interface UserAction {
  type: string;
  payload: string;
}

const rootReducer = (state = initialState, action: UserAction): IArticles => {
  switch (action.type) {
    case "ADD_ARTICLE": {
      return {
        articles: [action.payload, ...state.articles]
      };
    }
    default:
      return state;
  }
};

Ранее у меня возникла такая же проблема, как и у вас, потому что типы в редукторе неправильные.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...