【发布时间】:2022-03-23 17:51:49
【问题描述】:
我正在创建一个 sequelize 存储库,并且我有一个扩展 sequelize 模型的对象。
我能够执行以下操作将模型保存到数据库。
repository.create(myModel) // myModel being an instance of MyModel which extends sequelize model
现在我在打字稿中收到以下错误:
Argument of type 'MyModel' is not assignable to parameter of type 'CreationAttributes<MyModel>'.
Type 'MyModel' is not assignable to type 'Omit<any, string>'.
Index signature for type 'number' is missing in type 'MyModel'.ts(2345)
我正在做一些搜索,建议添加到 MyModel:
[key: number]: number;
当我这样做时,错误将更改为以下内容:
Argument of type 'MyModel' is not assignable to parameter of type 'CreationAttributes<MyModel>'.
Type 'MyModel' is not assignable to type 'Omit<any, string>'.
Index signature for type 'symbol' is missing in type 'MyModel'.ts(2345)
我可以通过更改对 create 的调用来绕过该错误:
repository.create({...myModel})
任何人都可以向我指出有关ts(2345) 它是什么的文档,也许是如何忽略它。或者以正确的方式解决问题?
使用扩展运算符,对我来说似乎有点混乱,但如果这是正确的解决方案,那很好。
模型定义:
import {
Column, DataType, ForeignKey, Model, Sequelize, Table,
} from 'sequelize-typescript';
import MediaResource from './media_resource';
import User from './users';
@Table({
tableName: 'videos',
timestamps: true,
version: true,
})
export default class Video extends Model {
@Column({
primaryKey: true,
autoIncrement: true,
type: DataType.INTEGER,
defaultValue: Sequelize.literal("nextval('videos_id_seq'::regclass)"),
})
id?: number;
@ForeignKey(() => MediaResource)
@Column({
field: 'media_resource_id',
allowNull: false,
type: DataType.INTEGER,
})
mediaResourceId?: number;
@Column({
allowNull: false,
type: DataType.STRING(191),
})
title?: string;
@Column({
allowNull: false,
type: DataType.STRING(2000),
})
url?: string;
@Column({
allowNull: true,
type: DataType.STRING(512),
})
description?: string;
@Column({
allowNull: false,
type: DataType.BOOLEAN,
})
is_3d?: boolean;
@Column({
allowNull: false,
type: DataType.BOOLEAN,
})
is_360?: boolean;
@ForeignKey(() => User)
@Column({
field: 'user_id',
allowNull: false,
type: DataType.INTEGER,
})
userId?: number;
@Column({
field: 'created_at',
allowNull: false,
type: DataType.DATE,
})
createdAt?: Date;
@Column({
field: 'updated_at',
allowNull: false,
type: DataType.DATE,
})
updatedAt?: Date;
}
存储库创建签名:
const db = DB.getInstance();
const videosRepository = db.getRepository(Video);
const transaction = await db.transaction();
try {
const saved = await videosRepository.create({ ...video }, { transaction });
await transaction.commit();
return saved;
} catch (err) {
await transaction.rollback();
if (err instanceof Error) logger.error(err.message);
throw new InternalServerError();
}
我们有一个 sequelize 单例,这就是 db,视频对象是从一个快速请求正文创建的。
这也曾经有效,我可以添加一个 ts-ignore 评论,它会有效。
续集:6.15.1 续集打字稿:2.1.2 打字稿:4.5.5
【问题讨论】:
-
你能显示模型定义和
repository.create签名 -
我更新了问题,感谢您的关注。
-
我只看到
create的内容,看不到参数
标签: node.js typescript sequelize.js