Настройка редуктора с машинописным реагированием редукса - PullRequest
0 голосов
/ 11 октября 2018

Я настраиваю ts с использованием приставки и сталкиваюсь с целым рядом проблем - в основном из-за недостатка знаний, но не могу найти много онлайн.Я вижу следующую ошибку:

Оператор '+' нельзя применить к типам 'CounterState' и '1'.

Код, который у меня естьследует:

interface CounterState {
  state: number;
}

const initialState: CounterState = {
  state: 0
}

interface Action {
  type: string;
}

export const counterReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

Если я обновлю это, оно будет работать, но, похоже, мне не нужно определять тип для этого состояния.Следующие работы

const initialState = 0;
interface Action {
  type: string;
}

export const counterReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
};

1 Ответ

0 голосов
/ 11 октября 2018

Хорошей практикой является всегда строго указывать ваши редукторы, как состояние, так и действия.

Здесь я показываю пример того, как правильно определенный редуктор и хранилище могут выглядеть вместе.Надеюсь, этот пример вместе с моими комментариями поможет вам.

import { Reducer } from "redux"; //This is just a Type we import from Redux.

interface IncrementAction {
  type: "INCREMENT"; //Define your action names
}

interface DecrementAction {
  type: "DECREMENT"; //Define your action names
}

type PossibleCounterActions = IncrementAction | DecrementAction; 
// The actions could/should be defined in another file for clarity


type CounterState = number;

const defaultState = 0;

// We bind the variable counterReducer to the Reducer type taken from redux.
// The our reducer code gets cleaner and we know the return type and arguments.
const counterReducer: Reducer<CounterState, PossibleCounterActions> = (state = defaultState, action) => {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}



// PS. This is not part of the question but it's
// a nice side-effect you can do when you have properly defined reducers.
// In the file where you create your store you can now get your store
// interface from the returntype of the redcuers using this pattern. 
const reducers = {
  counter: counterReducer
};

// Now we can get the entire store state from the declaration in the reducers.
export type IStoreState = { [k in keyof (typeof reducers)]: ReturnType<(typeof reducers)[k]> };

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