3

I'm getting some data from a server and then parsing it into TypeScript classes. I'm trying use some inheritance - every class needs to be able to report its type. Here's how that works:

This is the base class

import { PageElementType } from './page-element-type'

export class PageElement {
    pageElementType: PageElementType;
    constructor(aPageElementType: PageElementType) { 
        this.pageElementType = aPageElementType; 
    }
}

This is a derived class

import { PageElement } from './page-element.model'
import { PageElementType } from './page-element-type'

export class Metadata extends PageElement {
    id: number;
    body: string;

    constructor(){
        super(PageElementType.metadata);
    }
}

Here's the service function I call to parse the data

getExam(){
    let exam = this.http.get('http://orangeberry.hopto.org/api/Exam/1')
    .map((response:Response) => <Exam>response.json())
    .do(data => console.log(data));
    return exam;
}

Seems like I'm getting some sort of plain objects. I want meaningful, functional objects that actually follow the class definition. What's the simplest and most straight-forward way of achieving this for my case?

Torben Pi Jensen
  • 850
  • 9
  • 27
Dean Panayotov
  • 332
  • 4
  • 16

1 Answers1

1

A cast is only a hint for static code analysis but doesn't have any effect at runtime.

If you want the value to become an instance of a class, you need to create such an instance yourself:

.map((response:Response) => new Exam(response.json()))

where the constructor of the Exam class decomposes the JSON to its properties.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • I see. Thanks! I've read the 4 options for deserializing, pointed out here: http://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with-a-json-object. Last option seems like the best one to me. The variable names in my TypeScript classes match the json fields. Isn't there any straightforward way for me to parse the json to a pojo and then clone the values into my Typescript object? – Dean Panayotov Feb 18 '17 at 16:45
  • `Object.keys(json).map(k => this[k] = json[k])` if the JSON doesn't have nested objects. Actually I don't know too much about this part because I'm not using TypeScript myself. – Günter Zöchbauer Feb 18 '17 at 16:49
  • Yeah, the nested objects will prevent this 'automated' approach. Thanks Günter! – Dean Panayotov Feb 18 '17 at 16:53