gpt4 book ai didi

typescript - 续写 TypeScript 中的模型 getter

转载 作者:行者123 更新时间:2023-12-03 22:16:28 26 4
gpt4 key购买 nike

正确的使用方法是什么this.getDataValuegetter function使用 TypeScript 时的 Sequelize 模型?

这是我得到的错误:

Property 'getDataValue' does not exist on type 'string | DataTypeAbstract | DefineAttributeColumnOptions'.

Property 'getDataValue' does not exist on type 'string'.



我的模型定义:
import * as Sequelize from 'sequelize';
import sequelize from '../db-connection';

export interface IUserAttributes {
date_of_birth: Date;
name: string;
}

export interface IUserInstance extends Sequelize.Instance<IUserAttributes> {
date_of_birth: Date;
name: string;
}

const User = sequelize.define<IUserAttributes, IUserInstance>('user', {
name: {
type: Sequelize.STRING,
validate: {
notEmpty: true,
},
},
date_of_birth: {
get(): Date {
return new Date(this.getDataValue('date_of_birth'));
},
type: Sequelize.DATEONLY,
validate: {
isDate: true,
notEmpty: true,
},
},
});

export default User;

最佳答案

您需要为 this 指定类型在 getter 函数中

const User = sequelize.define<IUserAttributes, IUserInstance>('user', {
name: {
type: Sequelize.STRING,
validate: {
notEmpty: true,
},
},
date_of_birth: {
get(this: IUserInstance): Date {
return new Date(this.getDataValue('date_of_birth'));
},
type: Sequelize.DATEONLY,
validate: {
isDate: true,
notEmpty: true,
},
},
});

备注 this参数不会发送给 JS,它只是为了 typescript 编译器的好处。

关于typescript - 续写 TypeScript 中的模型 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48374032/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com