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

如何为含内联函数类的TypeScript代码添加正确类型注解?

TypeScript内联构造函数类型注解问题解决

问题重现

原始简化代码:

let x = 10;
const obj = new (function() {
  if(--x) return this.constructor();
  return {};
});

触发报错:

'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)

尝试手动注解后仍报错:

type myType = { constructor(): myType };
let x: number = 10;
const obj: myType = new (function(): myType {
  if(--x) return (this as myType).constructor();
  return {} as myType;
});

剩余报错:

'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.ts(7009)

错误原因

  1. 第一个报错是构造函数内的this未添加类型注解,TypeScript默认推断为any;
  2. 第二个报错的核心是:内联函数被用作构造函数时,必须显式声明其构造签名。之前定义的myType仅描述了实例的结构,但未定义该函数本身是可通过new调用的构造函数,TypeScript无法自动推断这个内联函数符合构造函数类型。

解决方案

需要同时给this添加类型注解,并给内联函数断言为带有构造签名的类型:

// 定义实例类型和对应的构造函数类型
interface MyType {
  constructor: new () => MyType;
}
type MyConstructor = new () => MyType;

let x: number = 10;
const obj: MyType = new (function(this: MyType): MyType {
  // 构造函数需通过new调用,修正原代码的调用方式
  if (--x) return new this.constructor();
  return {} as MyType;
} as MyConstructor);

关键说明

  • 给内联函数添加this: MyType注解,明确this的类型,解决this为any的报错;
  • 将内联函数断言为MyConstructor类型(即new () => MyType),告诉TypeScript这个函数是可被new调用的构造函数,解决“缺少构造签名”的报错;
  • 修正原代码中this.constructor()为new this.constructor(),符合构造函数的调用语义,同时避免TypeScript的隐式类型错误。

内容的提问来源于stack exchange,提问作者Bobby Morelli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:02:15