Sequelize.js:Model.build返回一个空白对象

时间:2018-09-07 07:42:03

标签: typescript sequelize.js

我正在使用Sequelize.js(4.38.0)和Typescript(3.0.3)。我还安装了@ types / sequelize软件包(在4.27.25版)。

我有以下代码,我无法翻译:

import Sequelize from 'sequelize'

const sequelize = new Sequelize('...');
const model = sequelize.define('Model', {a: Sequelize.INTEGER, b: Sequelize.INTEGER});

var instance = model.build({a: 1, b:1});
instance.save();

tsc返回以下错误:

 Property 'save' does not exist on type '{}'.

因此由于某种原因,build返回一个空白对象。 当我尝试使用create代替时,会出现相同的错误:create返回一个Promise,它解决了一个空白对象。

对此有何想法?

1 个答案:

答案 0 :(得分:1)

您需要显式指定泛型类型参数,这些定义不会尝试推断属性或实例类型的类型。

import Sequelize, { Instance } from 'sequelize'

const sequelize = new Sequelize('...');

interface Model {
    a: number;
    b: string;
}


const model = sequelize.define<Instance<Model>, Model>('Model', {a: Sequelize.INTEGER, b: Sequelize.INTEGER});

var instance = model.build({a: 1, b:'1'}); // b must be string error is now caught by typescript 
instance.save() // ok now