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

TypeScript数组类型属性调用size报错问题求助

修复数组访问size属性的错误并优化TypeScript代码

错误原因

你在Graph类的printData方法中访问this.nodes.size和this.edges.size报错,核心原因是数组类型没有size属性。你声明的nodes和edges是_Node[]、Edge[]数组,获取数组元素数量需要使用length属性,而size是Set、Map等集合类型专属的属性。

直接修复方案

将printData方法中的size替换为length即可解决报错:

// Graph.ts 中修改 printData 方法
printData() {
  const message =
    "This is a graph with " +
    this.nodes.length +
    " nodes and " +
    this.edges.length +
    " edges";
  console.log(message);
}

额外TypeScript代码优化

原代码存在类型模糊、类与接口未绑定等不规范问题,建议做以下优化以提升代码类型安全性:

1. 让_Node类实现对应接口并明确属性类型

// _Node.ts
interface _Node {
  data: Record<string, unknown>; // 替换any为更具体的类型,可根据业务需求调整
  neighbours: number[];
}

class _Node implements _Node {
  data: Record<string, unknown>;
  neighbours: number[];

  constructor(data: Record<string, unknown>) {
    this.data = { ...data };
    this.neighbours = [];
  }
}

export { _Node };

2. 优化Edge类的类型定义

// Edge.ts
interface Edge {
  start: number;
  end: number;
  data: Record<string, unknown>;
}

class Edge implements Edge {
  start: number;
  end: number;
  data: Record<string, unknown>;

  constructor(start: number, end: number, data: Record<string, unknown>) {
    this.start = start;
    this.end = end;
    this.data = { ...data };
  }
}

export { Edge };

3. 完善Graph类的类型绑定与代码简洁性

// Graph.ts
import { _Node } from "./_Node";
import { Edge } from "./Edge";

interface Graph {
  nodes: _Node[];
  edges: Edge[];
}

class Graph implements Graph {
  nodes: _Node[];
  edges: Edge[];

  constructor(nodes: _Node[], edges: Edge[]) {
    this.nodes = nodes;
    this.edges = edges;
    // this.printData();
  }

  printData() {
    // 使用模板字符串替代字符串拼接,代码更简洁
    const message = `This is a graph with ${this.nodes.length} nodes and ${this.edges.length} edges`;
    console.log(message);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:27:33