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

TypeScript如何遍历两个对象的键?Vector类语法报错问题求解

报错根源分析

  • 第一个变量x在赋值前被使用报错:TypeScript静态分析无法保证for...in循环一定会执行并完成对x、y两个变量的赋值,你声明变量时仅指定了类型未赋初始值,因此触发了未赋值就使用的校验规则。
  • 第二个不能用于索引类型'Vector'报错:component推导的类型是keyof this,this的类型在类方法中是动态的(如果有子类继承Vector,this会指向子类实例类型),和明确声明为Vector类型的参数v的索引类型不匹配,因此TS判定该索引操作不安全。

符合TypeScript规范的正确写法

你的Vector类目前只有x、y两个固定属性,完全不需要用for...in遍历,直接读写属性即可,写法更简洁也没有类型问题:

export class Vector {
  x: number;
  y: number;

  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }

  add(v: Vector): Vector {
    return new Vector(
      this.x + v.x,
      this.y + v.y
    );
  }
}

如果你后续要扩展成支持多维度的向量,需要保留遍历逻辑,可以采用类型断言+初始值的写法解决报错:

export class Vector {
  x: number;
  y: number;
  // 后续可扩展z等属性

  constructor(x = 0, y = 0) {
    this.x = x;
    this.y = y;
  }

  add(v: Vector): Vector {
    // 给初始值避免未赋值报错
    let x = 0, y = 0;
    // 把component断言为Vector的合法键名
    for (const component in this) {
      const key = component as keyof Vector;
      if (key === 'x') {
        x = this[key] + v[key];
      } else if (key === 'y') {
        y = this[key] + v[key];
      }
    }
    return new Vector(x, y);
  }
}

内容的提问来源于stack exchange,提问作者Luis Sulbarán

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 02:06:06