Skip to content

undefined attributes following typescript example #11675

Closed

Description

@nicgirault

Issue Description

What are you doing?

// this is a copy of https://sequelize.org/master/manual/typescript.html
import { Sequelize, Model, DataTypes, BuildOptions } from 'sequelize';
import { HasManyGetAssociationsMixin, HasManyAddAssociationMixin, HasManyHasAssociationMixin, Association, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin } from 'sequelize';

class User extends Model {
  public id!: number; // Note that the `null assertion` `!` is required in strict mode.
  public name!: string;
  public preferredName!: string | null; // for nullable fields

  // timestamps!
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;

  // Since TS cannot determine model association at compile time
  // we have to declare them here purely virtually
  // these will not exist until `Model.init` was called.

  public getProjects!: HasManyGetAssociationsMixin<Project>; // Note the null assertions!
  public addProject!: HasManyAddAssociationMixin<Project, number>;
  public hasProject!: HasManyHasAssociationMixin<Project, number>;
  public countProjects!: HasManyCountAssociationsMixin;
  public createProject!: HasManyCreateAssociationMixin<Project>;

  // You can also pre-declare possible inclusions, these will only be populated if you
  // actively include a relation.
  public readonly projects?: Project[]; // Note this is optional since it's only populated when explicitly requested in code

  public static associations: {
    projects: Association<User, Project>;
  };
}

const sequelize = new Sequelize('mysql://root:asd123@localhost:3306/mydb');

class Project extends Model {
  public id!: number;
  public ownerId!: number;
  public name!: string;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

class Address extends Model {
  public userId!: number;
  public address!: string;

  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

Project.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED, // you can omit the `new` but this is discouraged
    autoIncrement: true,
    primaryKey: true,
  },
  ownerId: {
    type: DataTypes.INTEGER.UNSIGNED,
    allowNull: false,
  },
  name: {
    type: new DataTypes.STRING(128),
    allowNull: false,
  }
}, {
  sequelize,
  tableName: 'projects',
});

User.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: new DataTypes.STRING(128),
    allowNull: false,
  },
  preferredName: {
    type: new DataTypes.STRING(128),
    allowNull: true
  }
}, {
  tableName: 'users',
  sequelize: sequelize, // this bit is important
});

Address.init({
  userId: {
    type: DataTypes.INTEGER.UNSIGNED,
  },
  address: {
    type: new DataTypes.STRING(128),
    allowNull: false,
  }
}, {
  tableName: 'address',
  sequelize: sequelize, // this bit is important
});

// Here we associate which actually populates out pre-declared `association` static and other methods.
User.hasMany(Project, {
  sourceKey: 'id',
  foreignKey: 'ownerId',
  as: 'projects' // this determines the name in `associations`!
});

Address.belongsTo(User, {targetKey: 'id'});
User.hasOne(Address,{sourceKey: 'id'});

async function stuff() {
  // Please note that when using async/await you lose the `bluebird` promise context
  // and you fall back to native
  const newUser = await User.create({
    name: 'Johnny',
    preferredName: 'John',
  });
  console.log(newUser.id, newUser.name, newUser.preferredName);

  const project = await newUser.createProject({
    name: 'first!',
  });

  const ourUser = await User.findByPk(1, {
    include: [User.associations.projects],
    rejectOnEmpty: true, // Specifying true here removes `null` from the return type!
  });
  console.log(ourUser.projects![0].name); // Note the `!` null assertion since TS can't know if we included
                                          // the model or not
}

My tsconfig:

"compilerOptions": {
    "outDir": "dist",
    "sourceMap": false,
    "allowJs": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false,
    "resolveJsonModule": true,
    "module": "commonjs",
    "strictNullChecks": true,
    "allowSyntheticDefaultImports": true,
    "lib": ["es7", "es2015", "dom"],
    "target": "es2015",
    "baseUrl": "."
  }

What do you expect to happen?

I expect ourUser.projects to be defined

What is actually happening?

console.log(ourUser.projects) // undefined

Context

Note that I also observe some strange behavior: when I add the flag raw: true in the query, the result looks like this:

{ 
  id: 1,
  createdAt: 2019-11-06T08:35:49.172Z,
  updatedAt: 2019-11-06T08:35:49.172Z,
  'projects.id': 1,
  'projects.ownerId': 1,
  'projects.createdAt': 2019-11-08T12:41:40.520Z,
  'projects.updatedAt': 2019-11-08T15:32:42.822Z
}

Environment

  • Sequelize version: 5.21.2
  • Node.js version: v10.16.3
  • Operating System: OSX
  • TypeScript version: 3.6.3

Issue Template Checklist

How does this problem relate to dialects?

  • I think this problem happens regardless of the dialect.
  • I think this problem happens only for the following dialect(s):
  • I don't know, I was using PUT-YOUR-DIALECT-HERE, with connector library version XXX and database version XXX

Would you be willing to resolve this issue by submitting a Pull Request?

  • Yes, I have the time and I know how to start.
  • Yes, I have the time but I don't know how to start, I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. nicgirault commented on Nov 14, 2019

    @nicgirault
    Author

    For French readers: this post helped me understand what is happening: https://openclassrooms.com/forum/sujet/proprietes-de-classe-avec-node-12-babel. It seems there is a conflict with babel class properties. Migrating to node v12 and removing babel plugin @babel/proposal-class-properties solved my issue

  2. added
    typescript
    on Jan 15, 2020
  3. reduardo7 commented on Sep 22, 2021

    @reduardo7

    What about it? How can I make it work?

  4. reduardo7 commented on Sep 22, 2021

    @reduardo7

    From https://sequelize.org/master/manual/typescript.html, the TypeScript definition for model initialization is correct, but the documentation is not correct!

    When you use the null assertion (public id!: number; // Note that the "null assertion" "!" is required in strict mode), this make the attribute as undefined at instance initialization.

    My idea is to force the model initialization using getDataValue() at Model Constructor and avoid to use the recommended null assertion.

    Example

    import {
      BuildOptions,
      Sequelize,
      Model,
      Optional,
    } from "sequelize";
    
    const sequelize = new Sequelize("mysql://root:asd123@localhost:3306/mydb");
    
    // These are all the attributes in the User model
    interface UserAttributes {
      id: number;
      name: string;
      //preferredName: string | null;
      preferredName?: string | null; // Make optional (`?:` the nullable fields
    }
    
    // Some attributes are optional in `User.build` and `User.create` calls
    interface UserCreationAttributes extends Optional<UserAttributes, "id"> {}
    
    class User extends Model<UserAttributes, UserCreationAttributes>
      implements UserAttributes {
      //public id!: number; // Note that the `null assertion` `!` is required in strict mode.
      public id: number;
    
      //public name!: string;
      public name: string;
    
      //public preferredName!: string | null; // for nullable fields
      public preferredName?: string | null; // Make optional (`?:` the nullable fields
    
      // timestamps!
      //public readonly createdAt!: Date;
      public readonly createdAt: Date;
    
      //public readonly updatedAt!: Date;
      public readonly updatedAt: Date;
    
      /**
       * Initialization to fix Sequelize Issue #11675.
       *
       * @see https://stackoverflow.com/questions/66515762/configuring-babel-typescript-for-sequelize-orm-causes-undefined-properties
       * @see https://github.com/sequelize/sequelize/issues/11675
       * @ref #SEQUELIZE-11675
       */
      constructor(values?: TCreationAttributes, options?: BuildOptions) {
        super(values, options);
    
        // All fields should be here!
        this.id = this.getDataValue('id');
        this.name = this.getDataValue('name');
        this.preferredName = this.getDataValue('preferredName');
        this.createdAt = this.getDataValue('createdAt');
        this.updatedAt = this.getDataValue('updatedAt');
      }
    }

    Source: https://stackoverflow.com/a/69289067/717267

  5. jaismith commented on Oct 30, 2021

    @jaismith

    also having this issue, does anyone know of a workaround or patch ETA? currently using .getDataValue to retrieve all my field values, which is somewhat messy...

  6. ephys commented on Nov 3, 2021

    @ephys
    Member

    @jaismith
    If you're using babel: This is an issue with babel setting the fields to undefined. Your options are to:

  7. jaismith commented on Nov 4, 2021

    @jaismith

    @jaismith If you're using babel...

    @ephys Not using babel, just ts-node plus tsconfig-paths.

    • node 16
    • typescript 4.4.3
    • tsconfig.target is esnext

    edit: I was able to get this working by setting my target to es6, is there a flag to set to get that working on a newer target?

  8. self-assigned this
    on Dec 30, 2021
  9. ephys commented on Dec 30, 2021

    @ephys
    Member

    @jaismith Have you tried using declare on your fields? (even with tsc/ts-node).

  10. ephys commented on Jan 2, 2022

    @ephys
    Member

    Merged #13877

  11. Sparrowan commented on Mar 20, 2024

    @Sparrowan
    • tsconfig

    This worked for me

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

Metadata

Metadata

Assignees

Labels

typescript

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions