我是typescript的新手,在这里我为我的一个项目添加了类型,它给了我一个类型的错误:"类型'string'不能赋值给类型'{model: {nodes: [];链接:[];};}’.ts (2322)
The expected type comes from property 'graph' which is declared here on type 'InitialGraphArticleState'
任何帮助/建议都是非常感谢的。
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
) {
}
在您的initialGraphArticleState
对象中,属性graph
与接口定义不匹配:您基本上是将string
分配给类型为{ model: { nodes: []; links: [] } }
的属性。
您可以按照如下方式更改对象初始化:
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: "",
};
或者更新你的接口定义以允许null
图形对象并初始化为它:
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: "",
};
考虑到你如何在减速机中使用graph
属性,我建议使用第一种解决方案,否则你需要在尝试使用其属性之前检查该属性是否为null。