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?

2
  • You expect an instance of Exam? Commented Feb 18, 2017 at 16:31
  • Yes. Sorry if my sample code is misguiding: The type functionality is implemented in other classes, not Exam itself. Exam contains an array of Metadata objects. Commented Feb 18, 2017 at 16:33

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I see. Thanks! I've read the 4 options for deserializing, pointed out here: stackoverflow.com/questions/22885995/…. 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?
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.
Yeah, the nested objects will prevent this 'automated' approach. Thanks Günter!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.