0

I am getting a JSON object with a JSON.parse function. I am facing the problem of converting the object to Data object. This is how Data is declared (it is simplified and the methods are omitted):

export class Data {
    private static _instance: AppData;
    private projects?: Project[] = Array();
    constructor() {
    }

    public static get Instance() {
       //create singleton
    }
}
export class Project {
    projectID: string;
    projectNumber: number;
    projectName: string;
    dateCreated: number;
    thumbnail: string;
    details?: Detail[] = [];


}
export class Detail {
    detailID:string;
    detailName: string;
    detailNumber:number;
    dateCreated:number;
    textElements?: Text[];

}


export class Text {
    text: string;
    textSize: number;
    transform: Transform[];
    transiton: Transiton[];
}

export class Transiton{
    name:string;
}
export class Transform{
    name:string;
}

Silly me, tried to typecast the whole object with as. Then I tried to write constructors, but it got terribly complicated due to each Data object having an array of Project objects, each project having an array of Detail objects... each detail having an array of Text objects and so on.

Is there a better way of doing this instead of just creating a ton of nested loops?

sanjihan
  • 5,592
  • 11
  • 54
  • 119
  • What's wrong with typecasting the whole object with `as`? – Borre Mosch Nov 10 '17 at 10:27
  • according to console.log, it doesn't work. For example, Projects[] is just an Array of objects and not array of Project objects. – sanjihan Nov 10 '17 at 10:33
  • TypeScript will always be compiled to JavaScript, and console.log will run after it has been compiled. It will never display any types. – Borre Mosch Nov 10 '17 at 10:44
  • it does display types. https://imgur.com/a/a0NGr . Those Projects were created with a constructor call. I also tried instanceof method on a previously typecasted object and it is not of the type to which it should be typecasted with as. – sanjihan Nov 10 '17 at 10:50
  • Right, I get what you are saying now. Unfortunately, you cannot use TypeScript to actually change the underlying JS type of your object in a simple way. For an actual answer to your question, you can refer to this question: https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class – Borre Mosch Nov 10 '17 at 11:02

0 Answers0