Sequelize版本:v6
我正在使用Sequelize.define来定义模型。其中一个属性存储为长文本,但通过getter和setter,它被用作应用层中的对象:
interface ModelNameAttributes {
modelId: string;
extras: string;
...
}
interface ModelNameCreationAttributes extends Optional<ModelNameAttributes, 'modelId'> {}
interface ModelNameInstance
extends Model<ModelNameAttributes, ModelNameCreationAttributes>,
ModelNameAttributes {}
type ModelNameStatic = typeof Model
& { associate: (models: any) => void }
& { new(values?: Record<string, unknown>, options?: BuildOptions): ModelNameInstance }
module.exports = (sequelize: Sequelize, DataTypes) => {
const ModelName = <ModelStatic>sequelize.define('ModelName', {
modelId: {
allowNull: false,
primaryKey: true,
type: DataTypes.UUID,
},
extras: {
type: DataTypes.TEXT('long'),
get: function (): {[key: string]: any} {
let val = this.getDataValue('extras');
return val && JSON.parse(val);
},
set: function (value: {[key: string]: any}): void {
this.setDataValue('extras', JSON.stringify(value));
},
},
...,
})
return ModelName;
});
当我尝试用创建记录时
const payload: ModelNameCreationAttributes = {
extras: { hello: 'hi' },
...
};
ModelName.create(payload, { transaction });
我在extras
下面看到一条红线,上面写着:
Type '{ [key: string]: any; }' is not assignable to type 'string'.
我该怎么办?非常感谢。
您需要在模型接口中更改extras
的定义,因为对于将使用它的代码,它应该看起来像一个对象,而不是字符串:
interface ModelNameAttributes {
modelId: string;
extras: Record<string, any>;
...
}
附言:您也可以在getter中使用Record<string, any>
而不是{[key: string]: any}
。