Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
Sequelize TypeScript getters and setters

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

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda