sequelize / sequelize-typescript

Decorators and some other features for sequelize

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

DataType.DOUBLE giving `string` instead of `number`

DavFeng1 opened this issue · comments

Issue

Relevent: sequelize/sequelize#8019
I have defined the following model using sequelize-typescript

// model.ts

interface IFooAttributes {
  id: string;
  bar: number;
  createdAt: Date;
}

type TFooCreationAttributes = Optional<IFooAttributes, 'id'>;

@Table({
  freezeTableName: true,
  timestamps: true,
  updatedAt: false,
  modelName: 'Foo',
})
class Foo
  extends Model<IFooAttributes, TFooCreationAttributes>
  implements IFooAttributes
{
  @Column({
    allowNull: false,
    primaryKey: true,
    type: DataType.STRING,
  })
  id!: string;

  @Column({ allowNull: false, field: 'bar', type: DataType.DOUBLE })
  bar!: number;

  @Column({ allowNull: false, field: 'created_at', type: DataType.DATE })
  createdAt!: Date;
}

export default Foo;

and I also have a unit test which validates the types of the model fields are returned as expected:

// Foo.test.ts
describe('model', () => {
  it('can create an instance', async () => {
    const payload = {
      bar: 4,
      createdAt: new Date(),
    };

    const foo = await fooModel.create(payload);

    assert.strictEqual(foo.bar, payload.bar);
  });
});

The test above produces the following error

AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

'4' !== 4

which indicates that the value returned back from the model is a string. Even though the static type shown is number

Versions

  • sequelize: 6.30.0
  • sequelize-typescript: 6.1.5
  • typescript: 5.0.2

Issue type

  • bug report
  • feature request

Actual behavior

The value of the field marked as DOUBLE gives a string value

Expected behavior

The value of the DOUBLE field should give a number

I'm using postgres, and have added this to my code, but I still get string instead of number for DOUBLE/FLOAT.
However BIGINT can get number instead of string after adding these code

import { types } from 'pg';

types.setTypeParser(types.builtins.INT2, (value: string) => {
  return parseInt(value);
});

types.setTypeParser(types.builtins.INT4, (value: string) => {
  return parseInt(value);
});

types.setTypeParser(types.builtins.INT8, (value: string) => {
  return parseInt(value);
});

types.setTypeParser(types.builtins.FLOAT4, (value: string) => {
  return parseFloat(value);
});

types.setTypeParser(types.builtins.FLOAT8, (value: string) => {
  return parseFloat(value);
});

types.setTypeParser(types.builtins.NUMERIC, (value: string) => {
  return parseFloat(value);
});

Not sure if it related, but DATEONLY is also stays as string.