【问题标题】:Argument of type '{ title: string; description: string; }' is not assignable to parameter of type '{ id: {}; title: {}; description: {}; }'类型参数 '{ title: string;描述:字符串; }' 不可分配给类型为 '{ id: {} 的参数;标题: {};描述: {}; }'
【发布时间】:2019-07-03 14:01:24
【问题描述】:

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

【问题讨论】:

  • 删除这个:allowNull: false for id
  • 我试过了,但我又遇到了同样的问题。
  • 在我的回答中查看我的更新

标签: javascript typescript express sequelize.js


【解决方案1】:

Sequelize 会默认你的表有一个 id 主键属性

您可以选择只删除id,sequelize 将默认处理它。

或者你可以...

对象的 id 属性不需要有allowNull: false。这是由 sequelize 自动处理的。

拥有allowNull: false 将使您在创建对象时检查id 属性是否存在,并且从逻辑上讲它不存在,因为稍后将添加该属性。

改变这个:

id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
}

到这里:

id: {
     type: Sequelize.INTEGER,
     autoIncrement: true,
     primaryKey: true
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2021-06-16
    • 2021-09-07
    • 2021-09-06
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多