我正在尝试使用 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: {};标题: {};描述: {};我该如何解决。没有 typescript 就可以了。
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;
最佳答案
Sequelize will assume your table has a id primary key property by default
您可以选择只删除
id
并且 sequelize 将默认处理它。或者你可以...
对象的 id 属性不需要有
allowNull: false
。这是 sequelize 自动处理的事情。当您创建对象时,拥有
allowNull: false
将使 sequelize 检查 id
属性是否存在,并且在逻辑上它不会存在,因为稍后会添加该属性。改变这个:
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
}
对此:
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
}
关于javascript - '{ title: string; description: string; }' 类型的参数不可分配给 '{ id: {}; title: {}; description: {}; }' 类型的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607466/