Andreas
Andreas

Reputation: 309

Sequelize.js: Model.build returns a blank object

I am using Sequelize.js (4.38.0) with Typescript (3.0.3). I also have the package @types/sequelize (at version 4.27.25) installed.

I have the following code which I cannot transpile:

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 returns with the following error:

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

So for some reason, build returns a blank object. When I try to use create instead, the same error appears: create returns a Promise which resolves a blank object.

Any thoughts on that?

Upvotes: 1

Views: 530

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249486

You need to specify the generic type parameters explicitly, the definitions make no attempt to infer the types for the attributes or the instance type.

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

Upvotes: 1

Related Questions