jeril
jeril

Reputation: 1253

Pass Object to redux store in typescript - type mismatch

I have got a function like this and I am trying to pass datum object to a redux store without the typescript complaining
import { TreeNodeDatum } from 'react-d3-tree/lib/types/common';
import { HierarchyPointNode } from 'd3-hierarchy';

const handleNodeClick = (datum: HierarchyPointNode<TreeNodeDatum>) => {

   //I am trying to pass datum to redux store
   dispatch(saveNode(datum)); 

/* Here typescript is complaining that Argument of type 
   HierarchyPointNode<TreeNodeDatum>' is not assignable to parameter of type 'node'.
   Types of property 'data' are incompatible. Type 'TreeNodeDatum' is missing the 
   following properties from type 'HierarchyPointNode<TreeNodeDatum>': x, y, links, data, 
   and 14 more. 
*/
}

I would like to know how do I pass the above datum object to a redux store without typescript complaining

My redux slice looks like this
interface node {
  data: HierarchyPointNode<TreeNodeDatum> | undefined;
  depth: number;
  height: number;
  parent: any;
  x: number;
  y: number;
}

const initialState: node = {
  data: {},
  depth: 0,
  height: 0,
  parent: null,
  x: 0,
  y: 0,
};

export const NodeSlice = createSlice({
  name: 'node',
  initialState,
  reducers: {
    saveNode: (state, action: PayloadAction<node>) => {
      state.data = action.payload.data;
      state.depth = action.payload.depth;
      state.height = action.payload.height;
      state.x = action.payload.x;
      state.y = action.payload.y;
    },
  },
});

Upvotes: 0

Views: 124

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

Need to assign to individual property. saveNode expects the type of interface node which has a data property with the corresponding type.

dispatch(saveNode({data: datum})); 

also make sure to pass the remaining properties required by the node interface.

Upvotes: 1

Related Questions