Skip to content

Sequelize with TypeScript - class fields undefined #10579

Closed

Description

@petrovi4

What are you doing?

I'am using Babel for code compilation + TypeScript for type-checking.
Two scenarios:

  1. Using define, which is "really wouldn't recommend this" (according types/test/define.ts comments)
interface User extends Model {
	id: number;
	login: string;
}

type UserModel = {
	new (): User;
} & typeof Model;

const User = sequelize.define(
	'User',
	{ login: DataTypes.STRING	},
	{ tableName: 'user' }
) as UserModel;
  1. Using new approach (based on code, found in the types/models/User.ts)
export class User extends Model {
	public id: number;
	public login: string;
}

User = User.init(
	{ login: DataTypes.STRING },
	{	sequelize, tableName: 'user' }
);

In DB (Postgres) I have one row with login 'admin'.

For the test, I use this function.

async function test() {
	const user = (await User.findOne()) as User;
	console.log('login', user.login, user.get('login'));
}
test();

What do you expect to happen?

It is logical that in both scenarios I should get

login admin admin

What is actually happening?

However, if in "modern", second approach I see

login undefined admin

And if I print console.log(user) I see

user1 User {
  dataValues:
   { id: 1,
     login: 'admin',
     createdAt: 2019-03-18T23:00:33.516Z,
     updatedAt: 2019-03-18T23:00:33.516Z },
  _previousDataValues:
   { id: 1,
     login: 'admin',
     createdAt: 2019-03-18T23:00:33.516Z,
     updatedAt: 2019-03-18T23:00:33.516Z },
  _changed: {},
  _modelOptions:
   { timestamps: true,
     validate: {},
     freezeTableName: false,
     underscored: false,
     paranoid: false,
     rejectOnEmpty: false,
     whereCollection: null,
     schema: null,
     schemaDelimiter: '',
     defaultScope: {},
     scopes: {},
     indexes: [],
     name: { plural: 'Users', singular: 'User' },
     omitNull: false,
     sequelize:
      Sequelize {
        options: [Object],
        config: [Object],
        dialect: [PostgresDialect],
        queryInterface: [QueryInterface],
        models: [Object],
        modelManager: [ModelManager],
        connectionManager: [ConnectionManager],
        importCache: {},
        test: [Object] },
     tableName: 'user',
     hooks: {} },
  _options:
   { isNewRecord: false,
     _schema: null,
     _schemaDelimiter: '',
     raw: true,
     attributes: [ 'id', 'login', 'createdAt', 'updatedAt' ] },
  isNewRecord: false,
  id: undefined,
  login: undefined }

Dialect: postgres
"sequelize": "^5.1.0",

upd:
Just tested with ts-node - everything works as it should.
Here is my .babelrc

{
	"sourceMaps": "inline",
	"retainLines": true,

	"presets": [
		[
			"@babel/preset-env",
			{
				"targets": {
					"node": true
				}
			}
		],
		"@babel/preset-typescript"
	],
	"plugins": [
		"@babel/plugin-proposal-optional-chaining",
		"@babel/plugin-proposal-object-rest-spread",
		"@babel/proposal-class-properties"
	]
}

Activity

  1. SimonSchick commented on Mar 20, 2019

    @SimonSchick
    Contributor

    Can you please post the code that is generated by babel for the user model?
    I have the suspicion it emits an this.login = undefined assignment because when I test the same code (in mysql) you provided in plain JS it works fine.

    ➜  sequelize git:(fix/ts-no-const-enum) node
    > void(S = require('./'))
    undefined
    > void(i = new S('mysql://root:pw@localhost/test123'))
    undefined
    > void(U = class User extends S.Model {}); void(U.init({ login: S.STRING }, { tableName: 'users', timestamps: false, sequelize: i }));
    undefined
    > void(U.findOne().then(u => console.log('login', u.login, u.get('login'))))
    undefined
    > Executing (default): SELECT `id`, `login` FROM `users` AS `User` LIMIT 1;
    login asd asd
    
  2. added a commit that references this issue on Mar 22, 2019
    db16cd5
  3. DanielRamosAcosta commented on Apr 24, 2019

    @DanielRamosAcosta

    I'm having the same problem @petrovi4, how did you solved it?

  4. DanielRamosAcosta commented on Apr 24, 2019

    @DanielRamosAcosta

    Here is the generated code by babel with the typescript preset:

    class OfficeModel extends _sequelize.Model {
      constructor(...args) {
        super(...args);
    
        _defineProperty(this, "id", void 0);
    
        _defineProperty(this, "field1", void 0);
    
        _defineProperty(this, "field2", void 0);
    
        _defineProperty(this, "createdAt", void 0);
    
        _defineProperty(this, "updatedAt", void 0);
      }
    
    }

    I believe the problem is that the super call sets the fields, but then they're setted to undefined by the _defineProperty function :/

  5. DanielRamosAcosta commented on Apr 24, 2019

    @DanielRamosAcosta

    It's a problem generated by the babel-plugin-proposal-class-properties. Do you know any what to fix this @SimonSchick? Maybe we can call a setup method from the constructor.

  6. DanielRamosAcosta commented on Apr 24, 2019

    @DanielRamosAcosta

    @SimonSchick It might be useful to call the _initValues from the child class?

  7. DanielRamosAcosta commented on Apr 24, 2019

    @DanielRamosAcosta

    The only other solution I see, is remove the babel-plugin-proposal-class-properties and upgrade to node 12 which supports class properties natively 😕

  8. Telokis commented on May 10, 2019

    @Telokis

    @DanielRamosAcosta Did you manage to make it work? Babel complains that babel-plugin-proposal-class-properties is not found even though I am using Node 12.

  9. DanielRamosAcosta commented on May 11, 2019

    @DanielRamosAcosta

    @Telokis I wasn't using static nor class properties that much, so I ended removing the babel-plugin-proposal-class-properties... bad solution 😢

  10. Telokis commented on May 11, 2019

    @Telokis

    @DanielRamosAcosta Thanks for the answer

  11. aaahrens commented on Oct 15, 2019

    @aaahrens

    Any solution to this by any chance? I am running this with nextjs and it makes a lot of boilerplate ; ;

  12. Telokis commented on Oct 15, 2019

    @Telokis

    @aaahrens If I remember correctly, a solution was to do it this way:

    export class User extends Model {
    	public id: number = this.id;
    	public login: string = this.login;
    }

    Even though it's not pretty.

  13. 22 remaining items

  14. swarthy commented on Jun 21, 2021

    @swarthy
    Contributor

    Same issue with raw Typescript example starting version 4.3, because now tsc generates empty fields

    class User extends sequelize_1.Model {
      id
      name
      preferredName
      createdAt
      updatedAt
      getProjects
      addProject
      hasProject
      countProjects
      createProject
      projects
      static associations
    }
    

    instead of

    class User extends sequelize_1.Model {}
    
  15. EtienneK commented on Jun 28, 2021

    @EtienneK

    Experiencing the same issue. Please reopen.

  16. dfyz011 commented on Aug 2, 2021

    @dfyz011

    Please reopen, I still don't see any normal solution

  17. DanielRamosAcosta commented on Aug 2, 2021

    @DanielRamosAcosta

    For me, the solution has been stop using sequelize, and change to MikroORM

  18. rudymalhi commented on Aug 16, 2021

    @rudymalhi

    The solution for me was to set "target": "ES2020" in tsnconfig.json (it was set to ESNEXT)

  19. edrpls commented on Aug 27, 2021

    @edrpls

    This is not really a solution, but dropping babel in favor of esbuild fixed this for me, plus, it's less configuration than babel+webpack.

  20. ortonomy commented on Sep 22, 2021

    @ortonomy

    @pieczorx can you tell me how you came up with this?

    export function restoreSequelizeAttributesOnClass(self: Model, newTarget, values, options): void {
      self._initValues(values, options || {});
      Object.keys(self.constructor.associations).forEach(key => {
        const association = self.constructor.associations[key]
        Object.values(association.accessors).forEach(accessor => {
          delete self[accessor]
        })
        association.mixin(self.constructor.prototype)
      })
    }
    

    Problem here:

    self._initValues(values, options || {});

    _initValues is not a valid property on the Model type and the typescript compiler complains.

  21. ortonomy commented on Sep 22, 2021

    @ortonomy

    Why was this closed? It's September 2021 and I'm using Nuxt and despite following exactly the typescript setup in Sequelize, ALL of the fields in the class are undefined and lazy loading associations does not work. All broken...

  22. intrinety commented on Oct 24, 2021

    @intrinety

    I have the same problem when use class definition.
    I resolve this issue by change to the default way of defining a model. It older but works.
    I have tested for feature Transaction and Association still work. this is my solution.

    Nextjs version: 11.1.2
    Sequelize: 6.6.5
    Typescript: 4.4.4

    import sequelize from "db/connection";
    import { DataTypes, Model, Optional } from "sequelize";
    
    /* ------ All Attributes Types -----*/
    interface RewardAttributes {
      id: number;
      title: string;
      description: string;
    }
    
    /* ------ Specify Optional Attributes Types ----------*/
    interface OptionalRewardAttributes extends Optional<RewardAttributes, "id"> {}
    
    /* ------ Declare an interface for our model that is basically what our class would be ------*/
    interface RewardBaseType
      extends Model<RewardAttributes, OptionalRewardAttributes>,
        RewardAttributes {}
    // Or you can pass the same type to all generic props like this
    // interface RewardBaseType extends Model<RewardAttributes, RewardAttributes>, RewardAttributes {}
    
    const RewardModel = sequelize.define<RewardBaseType>(
      "rewards",
      {
        id: {
          type: DataTypes.INTEGER.UNSIGNED,
          autoIncrement: true,
          primaryKey: true,
        },
        title: {
          type: DataTypes.STRING(200),
          allowNull: false,
        },
        description: {
          type: DataTypes.TEXT,
          allowNull: true,
        },
      },
      {
        freezeTableName: true,
        timestamps: true,
        createdAt: "created_at",
        updatedAt: "updated_at",
      }
    );
    
    export default RewardModel;
  23. ephys commented on Dec 29, 2021

    @ephys
    Member

    I'm reopening to document the workaround (see #10579 (comment)).

    Note that this is regarding the issue with babel. If you're experiencing the issue with a different transpiler, please open another bug report with all the necessary information.

  24. reopened this on Dec 29, 2021
  25. self-assigned this
    on Dec 29, 2021
  26. ephys commented on Jan 2, 2022

    @ephys
    Member

    Closed by #13877

  27. eungook commented on Nov 18, 2022

    @eungook

    try esbuild instead of babel. it works for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

existing workaroundtypescript

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions