2016-09-20 58 views
3

此刻我尝试开发我的第一个反应& redux和typescript示例,但我坚持在动作的声明。打字稿编译器仍会一遍又一遍地抛出相同的错误。redux-actions Typescript声明一个动作

也许我错过了这个概念的一些东西。

该代码基于this教程。

会很高兴任何帮助

graphActions.ts

/// <reference path="../../../typings/index.d.ts"/> 

import { createAction, Action } from 'redux-actions'; 
import * as _ from 'lodash'; 
import {IGraphObject} from "../components/graph/GraphObject"; 
import {Graph} from "../models/Graph"; 
import {ADD_GRAPH} from "../constants/ActionTypes"; 

const addGraph = createAction<Graph>(
    ADD_GRAPH, 
    (graph: IGraphObject) => ({graphObject: graph}) 
); 

export { 
    addGraph 
} 

Graph.ts

import {IGraphObject} from "../components/graph/GraphObject"; 

export type Graph = { 
    id?: number; 
    graphObject: IGraphObject 
} 

GraphObject.ts

export interface IGraphObject { 
    id?: number; 
    graphConfig: IGraphConfig; 
    graphInstance: any; 
    initGraph(container: HTMLElement); 
    addShape(shape: ICustomShapeElement); 
} 

的打字稿编译器会引发

(11,5): error TS2345: Argument of type '(graph: IGraphObject) => { graphObject: IGraphObject; }' is not assignable to parameter of type '(...args: { id?: number; graphObject: IGraphObject; }[]) => { id?: number; graphObject: IGraphObj...'. 
    Types of parameters 'graph' and 'args' are incompatible. 
    Type '{ id?: number; graphObject: IGraphObject; }' is not assignable to type 'IGraphObject'. 
     Property 'graphConfig' is missing in type '{ id?: number; graphObject: IGraphObject; }'. 

回答

1

解决了它。看看redux-actions的类型帮助了我。

终极版-动作分型

export function createAction<Input, Payload>(
     actionType: string, 
     payloadCreator?: PayloadCreator<Input, Payload> 
): (...args: Input[]) => Action<Payload>; 

const addGraph = createAction<IGraphObject, Graph>(
    ADD_GRAPH, 
    (graphObject: IGraphObject) => ({graphObject: graphObject}) 
); 
-1

我认为这个问题是在这里:

const addGraph = createAction<Graph>(
    ADD_GRAPH, 
    (graph: IGraphObject) => ({graphObject: graph}) 
); 

你传递一个IGrapObject作为匿名函数的参数和功能的预期收益值是Graph类型。

要使其工作,您的类Graph必须执行IGraphObject

但我认为最好的是,如果你将返回图表,就像这样:

const addGraph = createAction<Graph>(
    ADD_GRAPH, 
    (graph: Graph) => ({graphObject: graph}) 
); 

而且移动性能graphConfiggraphInstance到图形,也许改变addShape功能,因此它是IcustomShapeElement一个数组并将其添加到Grap中。

这有道理吗?

//丹尼尔

+0

为了Redux存储中的图是一个简单的类型,应包含更复杂的图形的实例。 我想实现的是:用户单击addGraph按钮=>我创建一个graphObjectInstance并将其分派到redux商店。像在这个例子中,它应该创建一个字符串的Todo –

+0

好吧,那么我认为它应该是addGraph = createAction ,如果我理解正确。 – Daniel

+1

解决了它。看看redux操作的index.d.ts帮助了我。 'const addGraph = createAction ' –