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

如何创建嵌套的TS类型?string和cityType无类型重叠报错如何解决?

问题原因

你当前定义的routeType是包含city数组和_id的对象类型,和你期望的「route本身就是城市数组」的结构不匹配,TS在做类型校验时检测到操作的类型和声明类型无重叠,就抛出了对应错误。

解决方案

分两种场景调整类型定义即可:

  • 场景1:不需要给route数组附加独立的_id字段
    直接将routeType声明为城市类型的数组:
type cityType = {
  name:  string,
  type: number,
  coords: {
    x: number,
    y: number,
  },
  _id: string
}

type routeType = cityType[]

调整后可直接按照const route: routeType = [city1, city2, ...]的形式赋值使用,类型校验完全匹配。

  • 场景2:需要给route数组附加独立的_id字段(数组本身携带id属性)
    用交叉类型定义:
type cityType = {
  name:  string,
  type: number,
  coords: {
    x: number,
    y: number,
  },
  _id: string
}

type routeType = cityType[] & { _id: string }

赋值示例:

const route: routeType = Object.assign([city1, city2], { _id: '路由唯一id' })

额外说明

如果你的报错是因为判断城市id是否在路由城市列表时触发,那无需调整类型定义,直接把判断逻辑从类似route.city.includes(cityId)改成route.city.some(city => city._id === cityId)即可解决类型不匹配问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:39:03