如何在TypeScript中结合传统构造函数+原型使用new关键字
解决方法
直接给这个传统构造函数添加TypeScript类型声明,就能让TS识别它的构造签名,不用转class也不用// @ts-ignore,具体修改步骤如下:
1. 定义构造函数和实例的类型接口
先引入THREE的类型,然后定义两个接口:一个描述实例类型,一个描述构造函数的签名:
import * as THREE from 'three'; // 定义TextAnimation的实例类型,继承THREE.Mesh的所有属性方法 interface TextAnimation extends THREE.Mesh {} // 定义构造函数的类型,声明它可以被new调用,接收几何参数并返回实例 interface TextAnimationConstructor { new(textGeometry: THREE.BufferGeometry): TextAnimation; prototype: TextAnimation; }
2. 修改原构造函数的类型标注
把原构造函数的this类型和参数类型替换成具体类型,再通过类型断言让函数符合构造函数类型:
// 重写构造函数的类型标注 const TextAnimation = function(this: TextAnimation, textGeometry: THREE.BufferGeometry) { // 调用父类构造函数完成初始化 THREE.Mesh.call(this, textGeometry); // 这里保留你的原有业务代码 } as unknown as TextAnimationConstructor; // 原型继承的代码保持不变 TextAnimation.prototype = Object.create(THREE.Mesh.prototype); TextAnimation.prototype.constructor = TextAnimation; export default TextAnimation;
核心要点:
- 用
TextAnimation接口继承THREE.Mesh,确保实例能兼容THREE网格的所有操作。 TextAnimationConstructor明确告诉TS:这个函数可以用new关键字调用,参数是几何体,返回对应实例。- 类型断言
as unknown as TextAnimationConstructor是为了绕开TS对普通函数不能作为构造函数的默认检查,同时保证类型正确。 - 把原代码里的
any换成具体的THREE.BufferGeometry(如果你的几何体是其他类型,对应调整即可),还能顺便提升代码的类型安全性。
改完之后,在MagicText.ts里调用new TextAnimation(geometry)就不会再出现TS7009错误了。
内容的提问来源于stack exchange,提问作者Kristi Jorgji
相关产品推荐
相关产品推荐

