Sequelize TypeScript getters and setters

Viewed 356

Environment

  • Sequelize version: 6.6.5
  • Node.js version: 14.17.6
  • If TypeScript related: 4.4.3
  • Dialect sqlite

When using typescript and getters/setters, if the column DataType does not match the interface/attribute type, typescript throws an error.

Example:

interface IUserAttributes {
  id: number;

  registeredAtIp: string;
}

interface IUserCreationAttributes extends Optional<IUserAttributes, 'id'> {}

class User extends Model<IUserAttributes, IUserCreationAttributes> implements IUserAttributes {
  public id!: number;
  
  public registeredAtIp!: string;
}

User.init(
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      unique: true,
    },
    registeredAtIp: {
      type: DataTypes.INTEGER,
      allowNull: false,
      get(): string {
        return int2Ip(this.getDataValue("registeredAtIp"));
        //            ^
        // Argument of type 'string' is not assignable to parameter of type 'number'.ts(2345)
        // this: User
      },
      set(newIp: string): void {
        this.setDataValue("registeredAtIp", ip2Int(newIp));
        //                                         ^
        // Argument of type 'number' is not assignable to parameter of type 'string'.ts(2345)
        // (alias) ip2Int(ip: string): number
        // import ip2Int
      },
    },
  },
  { sequelize, tableName: "users" }
);

Shouldn't getDataValue return number as the column DataType is INTEGER and not string?

Setting the interface type to number fixes the error but I can't create a User which has the property as a string.

I want to know how to stop the error, aka this.getDataValue('registeredAtIp') should be of type number.

NOTE: I already know I can do as unknown as number but I shouldn't have to do such a thing.

Asked on github: https://github.com/sequelize/sequelize/issues/13522

0 Answers
Related