How to define VIRTUAL field using typescript models #15045
-
Hi, I'm trying to setup my model using typescript. This is base class for one of my model: export class Meal extends Model<InferAttributes<Meal>, InferCreationAttributes<Meal>> {
declare id: CreationOptional<string>;
declare title: string;
declare products?: NonAttribute<Product[]>;
declare created_at: CreationOptional<Date>;
declare updated_at: CreationOptional<Date>;
declare getProducts: HasManyGetAssociationsMixin<Product>;
}
And this is initialization: Meal.init({
id: {
type: new DataTypes.UUID,
defaultValue: new DataTypes.UUIDV4,
primaryKey: true,
},
title: {
type: new DataTypes.STRING(128),
allowNull: false
},
totalEnergy: {
type: new DataTypes.VIRTUAL,
get() {
// when I'm trying to use "this.products" or "this.whatever" it throws an error
},
set(/*value*/) {
throw new Error('Do not try to set the `companyname` value!');
}
},
created_at: DataTypes.DATE,
updated_at: DataTypes.DATE,
}, { sequelize, underscored: true }); Now how to define VIRTUAL field with getters and setters and read |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I don't think we have a good typing solution for this yet. Using This is a missing feature. We need to add In the meantime, I would recommend using |
Beta Was this translation helpful? Give feedback.
-
As an alternate, I ended up using the pattern in https://sequelize.org/docs/v6/other-topics/typescript/ -> fullName.
|
Beta Was this translation helpful? Give feedback.
I don't think we have a good typing solution for this yet. Using
NonAttribute
will make.init
complain that the property is present, and not adding it will make model methods (create, update, etc…) complain that no value is provided for the virtual attribute.This is a missing feature. We need to add
VirtualAttribute<>
In the meantime, I would recommend using
NonAttribute<>
& using// @ts-expect-error
on.init
if it complains