Ravi Kumar Ravi Kumar - 8 days ago 6
JSON Question

complex name of field of class in typescript

I have a class in typescript like this -

export class News {
title: string;
snapshot: string;
headerImage: string;
}


Now In my angular service i have a method which get list of news like this -

private searchNews(sortOrder : string, query? : string):Observable<News[]>{
return this.http.get(this.url+'?'+this.buildParams(sortOrder,10,0,query))
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'))
}


here is the json data i am getting from server -

[{
"jcr:path":"someurl",
"title":"Hello News",
"snapshot":"Here is a snapshot",
"headerImage":"image.png"
},
...
]


Now i want to add a field "path" in my news class which maps value of field "jcr:path" of json data.

But i can't write class like this -

export class News {
jcr:path:string;// I may write it as - path:string
title: string;
snapshot: string;
headerImage: string;
}


So is there way i can tell typescript to extract value of "path" field from "jcr:path" properties

Answer

You can define the property name as a string:

class News {
    'jcr:path': string;
    // ...
}