我正在尝试使用Sequelize创建模型。但是方法createPost()抛出错误:
Argument of type '{ title: string; description: string; }' is not assignable to parameter of type '{ id: {}; title: {}; description: {}; }'.
Property 'id' is missing in type '{ title: string; description: string; }' but required in type '{ id: {}; title: {}; description: {}; }'.
我不确定为什么created()方法要用作参数类型{́id:{};标题:{};说明:{};以及如何解决。没有打字稿就可以了。
import * as Sequelize from 'sequelize';
import sequelize from '../util/database';
const postTable = sequelize.define('post', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: {
type: Sequelize.STRING,
allowNull: false
},
description: Sequelize.STRING
});
class Post {
title: string;
description?: string;
constructor(title: string, description: string) {
this.title = title;
this.description = description;
}
static findAll() {
return postTable.findAll();
}
createPost(){
postTable.create({
title: this.title,
description: this.description
});
}
}
export default Post;
答案 0 :(得分:0)
Sequelize将默认假定您的表具有id主键属性
您可以选择仅删除id
,并在默认情况下由sequelize处理。
或者您可以...
不需要对象的id属性具有allowNull: false
。这是由续集自动处理的。
拥有allowNull: false
会在创建对象时对id
属性是否存在进行顺序检查,并且从逻辑上讲它不会存在,因为稍后会添加。
更改此:
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
}
对此:
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
}