我在文件 中有一个模型定义用户.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
在这种情况下在 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/