【问题标题】:Extending bookshelf model with typescript causes error使用打字稿扩展书架模型会导致错误
【发布时间】:2026-02-08 19:50:01
【问题描述】:

我在配置文件中实例化了这样的书架:

// irrelevant code omitted
const knex = Knex(knexfile[env]);

const bookshelf = Bookshelf(knex as any);

const { Model } = bookshelf;

export default Model;
export { bookshelf };

这很好用;所有的进口解决和出口工作。我创建了一个这样的模型:

import Model from '../config/bookshelf';

class Module extends Model<{id:number}> {
  table = 'modules';

  get tableName() { return this.table; }
}

但是,我从 TypeScript 收到错误消息 Type '{ id: string; }' is missing the following properties from type 'Model&lt;any&gt;': belongsTo, belongsToMany, count, destroy, and 41 more. 似乎 TypeScript 期望我为 Model 提供的类型必须定义它所扩展的 Model 类上的所有方法,但这似乎与 this * postthe DefinitelyTyped example。关于如何在不将所有 40 多岁的方法添加到模型类型的情况下解决此问题的任何想法?

提前致谢!

【问题讨论】:

    标签: typescript knex.js bookshelf.js


    【解决方案1】:

    您需要创建一个扩展 bookshelf.Model&lt;class&gt; 的新类:

    class Module extends Model<Module> {
        table = 'modules';
        public id: number = 0;
    
        get tableName() { return this.table; }
    }
    

    Playground

    虽然这很有趣 TypeScript 支持

    【讨论】: