如何解决导出模型并在模板上使用
我在文件 user.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 User
分配给Generic T
类的Repository
,但不能像类那样工作在这种情况下不会在打字稿中转换为type
。
为了说明,当您使用class
或为变量class
分配变量时,实际上返回的是constructor function
,而不是{{ 1}}。
例如-
type
使用ES5目标,将在日志下面生成-
class A {
name: string = "A"
}
let b = A;
console.log(b);
由于您的存储库类期望使用类型 ƒ A() {
this.name = "A";
}
,因此必须使用<T>
运算符:
typeof
在第二种情况下,模块的导出作为特殊的export default class UserRepository extends Repository<typeof User> {
}
返回。因此,您不能像使用(module namespace object
)那样使用它们。但是您可以将其分配给变量并使用它,就像您在下一行中所做的一样-
modules.User
有关该课程的更多信息,您可以refer the link
-
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。