TypeScript扩展collect.js泛型Collection类时遇多类报错求助
修复后的代码
首先将文件后缀改为.ts,并调整构造函数的默认值:
// CustomCollection.ts import { Collection } from 'collect.js'; import CustomModel from './CustomModel'; export default class CustomCollection extends Collection<CustomModel> { constructor(models: CustomModel[] = []) { super(models); } } // CustomModel.ts import { Model, ModelFields } from 'pinia-orm'; export default class CustomModel extends Model { static entity = 'custom'; declare id: number; declare name: string; declare description: string; static fields(): ModelFields { return { id: this.number(0), name: this.string(''), description: this.string(''), }; } } // 使用示例 const collection = new CustomCollection(); console.log(collection.first()); // 现在可正常调用父类方法
错误原因分析
TS2314: 泛型类型'Collection'需要1个类型参数
核心是文件后缀问题:你在.js文件中编写TypeScript语法,编译器无法正确解析泛型继承关系。改为.ts后缀后,TypeScript能正常识别Collection<CustomModel>的泛型参数。TS2554: 期望1个参数,但获得0个
collect.js的Collection构造函数要求传入一个可迭代对象(必填参数)。你将子类参数设为可选后,不传参时会传入undefined,不符合父类的参数要求。给models设置默认值= [],可保证始终传入合法的数组参数。TS2339: 类型'MyCustomCollection'上不存在属性'first'
同样是文件后缀导致的类型解析问题:.js文件中TypeScript不会按TS规则处理类的继承关系,导致父类Collection的原型方法类型无法被继承。改为.ts文件后,编译器能正确加载父类的类型定义。
疑问解答
若该类仅适配特定类型,是否仍需定义为泛型?
不需要。CustomCollection已经明确继承Collection<CustomModel>,相当于把泛型类实例化为针对CustomModel的具体类,无需再给CustomCollection添加泛型参数。为何已将参数设为可选,编译时仍要求传参?
子类参数可选只是允许外部不传参,但内部调用super()时必须传入符合父类要求的参数。collect.js的Collection构造函数参数是必填项,给子类参数设置默认值就能解决这个矛盾。为何无法识别父类方法?是否与方法挂载到函数原型而非类有关?
和原型挂载无关,核心是文件后缀导致的类型解析问题。collect.js的类型定义是标准类结构,方法都在原型上,但.js文件中TypeScript不会处理TS的继承类型逻辑,改为.ts文件即可解决。
内容的提问来源于stack exchange,提问作者Pablo Villalba

