I am calling an API in my local environment and I am getting the following response.
{
"data": {
"dailyStreakResponses": [
{
"date": 1658514600000,
"activity": 0,
"streak": null,
"videos": [],
"feedback": [],
"awards": [
{
"award": {
"id": 1,
"awardName": "Course1 Award",
"createdAt": 1658565639670,
"category": "AWARD"
},
"awardTime": 1658565639670
},
{
"award": {
"id": 2,
"awardName": "Course1 Certificate",
"createdAt": 1658565651055,
"category": "CERTIFICATE"
},
"awardTime": 1658565639670
}
]
}
]
},
"status": 200,
"statusText": "",
"headers": {...},
"config": {...},
"request": {},
"error": false
}
From this response, I only need the data part. So I created the following interface
export interface StudentDailyStreakResponse {
data : {
dailyStreakResponses: [{
date : number
activity : number
streak : number
videos : [{
id: number
activityName: string
}]
feedback : [{
commentId: number
comment: string
}]
awards : [{
award: {
id: number
awardName: string
}
}]
}]
}
}
Even after typecasting the response to StudentDailyStreakResponse I am getting so many fields in the response. How can I just get the data part ?
CodePudding user response:
There is no type casting in JavaScript. TypeScript does support type assertion but this is only for compilation time. you can use it like this:
const foo = res as StudentDailyStreakResponse;
However, for your purpose you can use class, like so:
export interface IStudentDailyStreakResponse {
data: {
dailyStreakResponses: [{
date: number
activity: number
streak: number
videos: [{
id: number
activityName: string
}]
feedback: [{
commentId: number
comment: string
}]
awards: [{
award: {
id: number
awardName: string
}
}]
}]
}
}
export class StudentDailyStreakResponse implements IStudentDailyStreakResponse {
data: {
dailyStreakResponses: [{
date: number
activity: number
streak: number
videos: [{
id: number
activityName: string
}]
feedback: [{
commentId: number
comment: string
}]
awards: [{
award: {
id: number
awardName: string
}
}]
}]
}
constructor(res: any) {
this.data = {
dailyStreakResponses: res.data?.dailyStreakResponses.map((d: any) => ({
date: Number(d.date),
activity: Number(d.activity),
streak: Number(d.streak),
videos: d.videos.map((v: any) => ({
id: Number(v.id),
activityName: String(v.activityName)
})),
feedback: d.feedback.map((f: any) => ({
commentId: Number(f.commentId),
comment: String(f.comment)
})),
awards: d.awards.map((a: any) => ({
award: {
id: Number(a.award.id),
awardName: String(a.award.awardName)
}
}))
}))
}
}
}