JSON类型的对象只有parse和stringify方法,但我想访问对象数据



我有一个包含NestJS、Typescript和Typeorm的项目。我正在使用以下类实体

class Event {
user: string,
createdAt: Date,
type: string,
data: JSON
}

在我的一个方法中,我进行了一个查询以获取一些事件,但我只想访问data属性的一些属性,因为该对象有很多我并不真正需要的信息。问题是,当我尝试访问json时,例如:receivedEvent.data.myPropertytypescript告诉我该属性在类型json中不可用。我能想到的唯一解决方案是将data属性的类型更改为字符串,并在查询后将其解析为json,但我想知道是否有其他解决方案。这是我用来查询事件的代码:

async getLogs(loanId: string): Promise<Event[]> {
const events = await this.eventRepository.find({
select: ['createdAt', 'user', 'type', 'data'],
where: {
type: In([
'early_payoff',
]),
data: Raw(
/* istanbul ignore next */
() => 'data->"$.GUID" = :id',
{ id: loanId },
),
},
order: {
id: 'DESC',
},
});
console.log(events);

return events.map(e=>{
/// This is where my problem is
const json: any = {"withdrawReason": e.data.withdrawReason}
return {...e, data: json}
});
}

我找到了这个问题的快速解决方案。我将event.data设置为另一个类型为的变量,之后Typescript不会抛出错误。

return events.map(e=>{
/// This is where my problem was
const json: any = e.data
const jsonData: any = {"withdrawReason": json.withdrawReason}
return {...e, data: jsonData}
});

最新更新