此刻我尝试开发我的第一个反应& redux和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);
}
typescript编译器抛出
(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; }'.
答案 0 :(得分:1)
解决了它。看看redux-actions打字对我有帮助。
redux-actions typings
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 :(得分:-1)
我认为问题在于:
const addGraph = createAction<Graph>(
ADD_GRAPH,
(graph: IGraphObject) => ({graphObject: graph})
);
您正在传递IGrapObject
作为该匿名函数的参数,并且该函数的预期返回值的类型为Graph
。
要使其成功,您的班级Graph
必须实施IGraphObject
。
但我认为最好的情况是你会返回Graph,就像这样:
const addGraph = createAction<Graph>(
ADD_GRAPH,
(graph: Graph) => ({graphObject: graph})
);
同时将属性graphConfig
和graphInstance
移动到Graph,也许更改addShape函数,使其成为IcustomShapeElement
的数组,并将其添加到Grap中。
这有意义吗?
//丹尼尔