TypeScript 2中导入文件扩展Array原型后类型不识别如何解决?
解决TypeScript中扩展Array原型方法后类型报错的问题
你遇到的这个报错是TypeScript类型系统的典型问题——它默认不会识别你给原生Array原型新增的方法,所以需要我们手动扩展它的类型定义。
先回顾下你的代码场景:
在extensions.js中扩展了Array原型:
Array.prototype.shuffle = function() { for (let i = this.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [this[i], this[j]] = [this[j], this[i]]; } }
在test.js中导入后使用时触发报错:
import 'extensions.js'; function() { var arr = []; // or new Array() arr.shuffle(); }
报错信息:
[ts] Property 'shuffle' does not exist on type 'any[]'. any
解决方案:扩展TypeScript的Array类型定义
最规范的做法是给Array接口添加类型声明,让TypeScript知道这个新增的方法。
方法1:在扩展文件中添加全局类型声明
如果你把extensions.js改成extensions.ts(或者保持JS文件,额外创建一个类型声明文件array-extensions.d.ts),添加以下内容:
// 全局扩展Array接口 declare global { interface Array<T> { // 声明shuffle方法的类型:无参数,返回值为void shuffle(): void; } } // 实现shuffle方法(如果是单独的d.ts文件,这部分不用写,只保留上面的声明) Array.prototype.shuffle = function() { for (let i = this.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [this[i], this[j]] = [this[j], this[i]]; } } // 必须导出一个空对象,让TypeScript将这个文件识别为模块(如果有import/export的话) export {};
这样处理后,整个项目中的所有Array类型都会自动拥有shuffle方法的类型提示,不会再报错。
方法2:临时类型断言(不推荐)
如果只是临时解决单个场景的报错,可以用类型断言强制告诉TypeScript这个数组有shuffle方法,但这种方法不够优雅,也无法复用类型:
import 'extensions.js'; function() { var arr = [] as any[] & { shuffle(): void }; arr.shuffle(); }
注意事项
- 如果你的扩展文件是模块(包含
import/export语句),必须用declare global包裹类型声明,否则只会在当前模块内生效。 - 类型声明文件(
.d.ts)需要放在TypeScript能识别的目录下(比如src目录,或者在tsconfig.json的include数组中配置)。
内容的提问来源于stack exchange,提问作者John Difool
相关产品推荐
相关产品推荐

