javascript -  '{ title: string; description: string; }' 类型的参数不可分配给  '{ id: {}; title: {}; description: {}; }' 类型的参数

标签 javascript typescript express sequelize.js

我正在尝试使用 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/

相关文章:

javascript - JSlint:在函数范围内重新定义 i

php - 使用 ajaxRequest.open 将变量发送到 php

javascript - jquery 将数组分成 4 组

Angular 动态形式可观察输入属性始终为空

angular - 如何从 Angular 中的 Observable 中提取数据

node.js - express.js 检查部分范围下载是否完成

javascript - 从 null 更新后 Highcharts 不显示工具提示

javascript - 用 Jest 模拟条件 window.open 函数调用

node.js - Express:逻辑或路由中

node.js - Sequelize 在更新时抛出无效值 [Function]