I'm new on typescript, here i have added types to a project of mine, it is giving me error on one of types at graph: "" : Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322)
The expected type comes from property 'graph' which is declared here on type 'InitialGraphArticleState'
any help/suggestion is appreaciated.
interface InitialGraphArticleState {
graph: { model: { nodes: []; links: [] } };
currentNode: string;
currentLink: string;
currentCameraNode: string;
currentCameraLinks: [];
floorplan: string;
}
const initialGraphArticleState: InitialGraphArticleState = {
graph: "",
currentNode: "",
currentLink: "",
currentCameraNode: "",
currentCameraLinks: [],
floorplan: "",
};
export function graphArticleReducer(
state = initialGraphArticleState,
action: graphArticleReducerAction
) {
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
In your initialGraphArticleState
object, the property graph
does not match the interface definition: You are basically a assigning a string
to a property of type { model: { nodes: []; links: [] } }
.
You can either change the object initialization as follow:
interface InitialGraphArticleState {
graph: { model: { nodes: [], links: [] } };
currentNode: string;
currentLink: string;
currentCameraNode: string;
currentCameraLinks: [];
floorplan: string;
}
const initialGraphArticleState: InitialGraphArticleState = {
graph: { model: { nodes: []; links: [] } },
currentNode: "",
currentLink: "",
currentCameraNode: "",
currentCameraLinks: [],
floorplan: "",
};
Or update your interface definition to allow a null
graph object and initialize to that instead:
interface InitialGraphArticleState {
graph: { model: { nodes: [], links: [] } } | null;
currentNode: string;
currentLink: string;
currentCameraNode: string;
currentCameraLinks: [];
floorplan: string;
}
const initialGraphArticleState: InitialGraphArticleState = {
graph: null,
currentNode: "",
currentLink: "",
currentCameraNode: "",
currentCameraLinks: [],
floorplan: "",
};
Considering how you are using the graph
property in the reducer, I would advise the first solution, otherwise you need to check that the property is not null before trying to use its properties.