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

如何在TypeScript中像JavaScript一样用函数创建对象?

在TypeScript中用函数构造对象的解决方法

你遇到的两个错误本质是TypeScript的类型检查机制导致的:

  • 'this' implicitly has type 'any':TypeScript无法自动推断构造函数内部this的类型,必须显式注解
  • 'new' expression, whose target lacks a construct signature:没有定义构造函数的实例类型,TS不知道new Box()会生成什么类型的对象

下面是两种符合需求的解决方案:

方案一:显式注解this类型+类型断言

// 定义Box实例的类型接口
interface Box {
  width: number;
  height: number;
}

// 给构造函数的this指定为Box类型,同时给参数添加类型注解
function Box(this: Box, a: number, b: number) {
  this.width = a;
  this.height = b;
}

// 通过类型断言让TS识别这是一个合法的构造函数
const box = new (Box as unknown as new (a: number, b: number) => Box)(3, 5);

方案二:定义构造函数签名(更规范)

// 定义Box实例的类型
interface Box {
  width: number;
  height: number;
}

// 定义构造函数的签名,指定new操作符的参数和返回值类型
interface BoxConstructor {
  new(a: number, b: number): Box;
}

// 实现构造函数并断言类型
const Box: BoxConstructor = function(this: Box, a: number, b: number) {
  this.width = a;
  this.height = b;
} as any;

// 正常使用new创建实例
const box = new Box(3, 5);

如果是简单场景,也可以直接用TypeScript的类实现,效果和JS构造函数一致,还能获得完整类型支持:

class Box {
  width: number;
  height: number;

  constructor(a: number, b: number) {
    this.width = a;
    this.height = b;
  }
}

const box = new Box(3, 5);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:11