typescript - 导出模型并在模板上使用

标签 typescript types model sequelize.js

我在文件 中有一个模型定义用户.ts

export default class User extends Model {
  public id?: string;
   ...

  public static setup(sequelize: Sequelize): void {
   ...
  }

  public static association(): void {
    ...
  }
}
我将它导入到 index.ts 文件导出到其他位置
export const models = {
  Address,
   ...
  User,
};
我正在尝试使用 models.User 模板中的类,我尝试了以下方法,但没有得到它的工作
1.
import Repository from '../../types/Repository';
import { models } from '../../models';

const { User } = models;

export default class UserRepository extends Repository<User> { // <- TS2749: 'User' refers to a value, but is being used as a type here. Did you mean 'typeof User'?

}
2.
import Repository from '../../types/Repository';
import { models } from '../../models';


export default class UserRepository extends Repository<models.User> { // <- TS2503: Cannot find namespace 'models'.

}
存储库类具有以下形状:
export default class Repository<T extends Sequelize.Model> {
 ...
}
- - 编辑 - -
3.(MBB指点)
import Repository from '../../types/Repository';
import { models } from '../../models';

const { User } = models;

export default class UserRepository extends Repository<typeof User> { // <- TS2344: Type 'typeof User' does not satisfy the constraint 'Model<any, any>'.   Type 'typeof User' is missing the following properties from type 'Model<any, any>': _attributes, _creationAttributes, isNewRecord, where, and 16 more.

}

如何使用/导出这些模型以在模板中使用它?

最佳答案

在第一种情况下 您正在分配 class UserGeneric TRepository类,这将不起作用,因为该类不会转换为 type在这种情况下在 typescript 中。
为了说明您何时使用 class或使用 class 分配一个变量那么你实际上得到的是constructor function这不是 type .
例如 -

class A {
    name: string = "A"
}

let b = A;
console.log(b); 
使用 ES5 目标,这将产生以下日志 -
 ƒ A() {
     this.name = "A";
 }
由于您的 Repository 类需要类型 <T>您必须使用 typeof运算符(operator):
export default class UserRepository extends Repository<typeof User> { 
}
在第二种情况下模块的导出作为特殊的 module namespace object 返回.所以你不能像你使用的那样使用它们( modules.User )。但是你可以将它分配给一个变量并使用它,你在下面的行中做了 -
const { User } = models;
更多类(class)信息可以 refer the link -

关于typescript - 导出模型并在模板上使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63582708/

相关文章:

python - 如何使用多个分类变量以 Python R 风格创建预测模型

python - 用 pre_save() 填充 django 字段?

typescript - 修改实现接口(interface)的对象(通过索引访问)的值时出现类型错误

oracle - Oracle 中合理的年份数据类型是什么?

c# - 将 T 限制为字符串和整数?

c++ - 在 C++ 中使用 T1 = unsigned T2 的奇怪结果

javascript - 从 Javascript 文件访问 MVC 的模型属性

reactjs - spread 参数必须具有元组类型或传递给 rest 参数 React

typescript - 具有抽象语法的 Visual Studio 代码

javascript - ESLint: 8.0.0 加载插件失败 '@typescript-eslint'