元素隐式具有“任何”类型,因为“数字”类型的表达式不能用于索引类型“{}”。.ts(7053) VUEJS

严酷的潘迪

我知道有多个此类问题,但我几乎尝试了所有方法,但仍然出现此错误。我在一个vue 项目中工作。我已将我的数据定义如下:

data(){
    return{
      nodes: {},
      edges:{},
      nextNodeIndex: 0,
      nextEdgeIndex: 0,
      selectedNodes: [],
      selectedEdges: [],
      graph: ref<vNG.Instance>() 
    }
  }

现在在一个方法中,我正在编写一个 addNode 函数

 addNode() {
      const nodeId = this.nextNodeIndex
      this.nodes[nodeId] = {
        name: String(nodeId),
        size: 16,
        color: "blue",
        label: true
      } 

该行this.nodes[nodeId]给出错误Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'.我发现的大多数解决方案都告诉将 dict 定义为,const dict = {key:string}但由于我在定义节点,data所以不能使用 const。

任何建议都非常感谢。

击中我

您可以显式键入的返回类型data

data(): { nodes: ..., ... } {

}

但这意味着你必须编写很多 TypeScript 可以推断的类型。

我宁愿接受一个断言:

nodes: {} as { [key: number]: { name: string; size: number; ... } },

甚至可能用于edges

edges: {} as { [key: number]: ... },

但是,看到键是数字,您可能需要考虑使用数组而不是对象。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章