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

TypeScript类成员为接口数组时length未定义问题排查

问题分析与解决方案

你代码里的问题很明确:类成员circles只声明了类型,但没有初始化数组实例。在TypeScript中,仅写circles: Circle[];时,这个属性默认值是undefined,并非空数组。直接调用this.circles.push()相当于在undefined上调用方法,会触发错误,后续的length自然也是undefined。

解决方法很简单,给circles初始化一个空数组,有两种常用方式:

方式一:声明时直接初始化

interface Point {
  x: number;
  y: number;
}
interface Circle {
  xy: Point;
  radius: number;
}

class Canvas {
  circles: Circle[] = []; // 直接初始化空数组
  constructor() {
    this.circles.push({
      xy: {
        x: 10,
        y: 10,
      },
      radius: 0,
    });

    console.log(this.circles.length); // 现在会输出1
  }
}

方式二:在构造函数内初始化

interface Point {
  x: number;
  y: number;
}
interface Circle {
  xy: Point;
  radius: number;
}

class Canvas {
  circles: Circle[];
  constructor() {
    this.circles = []; // 先初始化空数组
    this.circles.push({
      xy: {
        x: 10,
        y: 10,
      },
      radius: 0,
    });

    console.log(this.circles.length); // 现在会输出1
  }
}

两种方式都能解决问题,可根据代码习惯选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:05:22