You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript报ts2322错误:string类型不可分配给{model:{nodes:[];links:[]}}类型如何解决

错误原因

你在InitialGraphArticleState接口中声明的graph字段类型为包含model属性的对象结构,但初始值赋值为字符串类型的"",二者类型不匹配,因此触发ts(2322)类型错误。

解决方案

方案1:调整初始值匹配现有类型定义

如果业务逻辑中graph字段永远为包含model的对象结构,直接修改初始值为符合类型要求的空结构即可:

const initialGraphArticleState: InitialGraphArticleState = {
  graph: { model: { nodes: [], links: [] } },
  currentNode: "",
  currentLink: "",
  currentCameraNode: "",
  currentCameraLinks: [],
  floorplan: "",
};

方案2:调整接口类型适配多类型场景

如果业务逻辑中graph确实存在为字符串的场景,修改接口的graph字段类型为联合类型:

interface InitialGraphArticleState {
  graph: { model: { nodes: []; links: [] } } | string;
  currentNode: string;
  currentLink: string;
  currentCameraNode: string;
  currentCameraLinks: [];
  floorplan: string;
}

注意:使用联合类型后,后续代码访问graph的model属性前,需要先做类型判断窄化类型,比如if (typeof graph === 'object' && graph !== null),避免触发新的类型错误。

内容的提问来源于stack exchange,提问作者user1072745

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:24:10