无法在TypeScript + Redux中使用reducer创建商店

时间:2017-01-20 16:26:41

标签: typescript redux

我在使用redux和typescript创建商店时遇到了麻烦。这是actions.js:

import { Action } from 'redux';

export interface ITodoAction extends Action {
    todo:string;
}

export const ADD_TODO:string = 'ADD_TODO';
export function addTodo(todo:string):ITodoAction {
    return {
        type: ADD_TODO,
        todo
    };
}

我导出了名为ITodoAction的自定义操作的接口,为我的自定义属性todo扩展了Action:string。

这是reducers.js:

import { Reducer } from 'redux';
import { ITodo } from '../interfaces';
import { ITodoAction, ADD_TODO } from '../actions';

let id:number = 0;
const generateId = ():number => id++;

interface ITodoState {
    todos:Array<ITodo>
};

const defaultState:ITodoState = {
    todos: []
};

export function todoReducer(state:ITodoState = defaultState, action:ITodoAction):ITodoState {
    switch(action.type) {
        case ADD_TODO:
            return Object.assign({}, state, {
                todos: [
                    { id: generateId(), text: action.todo, completed: false },
                    ...state.todos
                ]
            });
        default:
            return state;
    }
}

我使用过去的actions.js fir中的ITodoAction来定义todoReducer。 todoReducer将返回ITodoState实例,如下所示:

{
   type: 'ADD_TODO',
   todos: [ ITodo{}, ITodo{}, ITodo{}, ... ]
}

这是我使用的ITodo界面:

export interface ITodo {
    id:number;
    todo:string;
    completed:boolean;
}

它只是包含id,text,complete的普通对象。我认为这似乎很好,但是当我尝试用这样的减速器创建商店时:

import { createStore } from 'redux';
import todoReducer from './reducers';

export const store = createStore(todoReducer);

它失败了:

Argument of type 'typeof "/.../typescript-todo/src/ts/reducers/index"' is not assignable to parameter of type 'Reducer<{}>'...
Type 'typeof "/./typescript-todo/src/ts/reducers/index"' provides no match for the signature '&lt;A extends Action&gt;(state: {}, action: A): {}'

看起来我必须修复我的减速机,但是我没有理解如何使用Reducer&lt; {}&gt;来定义减速器,每次我尝试都失败了类似消息,例如&#34; blablabla不是可分配给blablabla&#34;。

我想要的只是使用我的简单减速机,但为什么我不能? 它还没有使用combineReducer,此时它需要使用某种ReducerMap或其他东西,我不记得实际的界面是什么。

我发现了许多打字稿+ redux相关帖子,但他们没有使用Reducer&lt; {}&gt;或动作&gt; T&lt;喜欢什么,他们只是使用他们自己定义的Action和Reducer,但这些只是让我感到困惑,为什么他们没有使用Reducer和Action接口,以及它为什么有效?

不知何故,我找到了redux的类型声明,这就是Reducer&lt; {}&gt;的方式。看起来像:

export type Reducer<S> = <A extends Action>(state: S, action: A) => S;

尽可能我理解的是Reducer&lt; {}&gt;是一个返回状态的函数。那为什么我的todoReducer没有与他们合作?我尝试使用Reducer&lt; ITodoState&gt;,但它没有工作。

我现在真的很困惑,看起来我错过了一些大事,但是,哇,我真的不明白我错过了什么。 我从未想过将Redux与TypeScript一起使用会很困难。

我尽我所能,但看起来我需要一只手。任何建议都会非常感激。

1 个答案:

答案 0 :(得分:0)

修正了,只需将reducer导出为默认值,然后就可以了。