-1

What is the best/common way to cast a JSON into a class in Typescript with ES5 (no Object.assign()).

e.g.

export class Lesson{
 name:string;
 teacher:Teacher;
 date:Date;
 scholars:Array<string>; //or string[] ... I dont care
}

The JSON would look like:

{
 name:"LessonName",
 teacher:{name:"masterT", age:120},
 date:12345678912
 scholars:["Jim","Bob","Jimbo"]
}

In Typescript I can cast the JSON to a Object and even assign it straight to a Lesson object (!-horrible behaviour, but thats JS-!)

But the object don't have any methods for example.

e.g. So lesson.date.getTime() won't work.

So how to handle that correctly?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Gregor Sklorz
  • 1,645
  • 2
  • 19
  • 27
  • Possible duplicate of [How do I initialize a typescript object with a JSON object](https://stackoverflow.com/questions/22885995/how-do-i-initialize-a-typescript-object-with-a-json-object) – jcalz Sep 01 '17 at 17:27
  • This is the job for the `constructor` of a class. This way you can cast the date field into a Date object etc so you can do `new Lesson(attributes)` – Fotis Sep 01 '17 at 17:28

1 Answers1

0

Try

// first declare variable
var lesson: Lesson;

// and then assign that
lesson={
 name:"LessonName",
 teacher:{name:"masterT", age:120},
 date:12345678912
 scholars:["Jim","Bob","Jimbo"]
}

But the problem is that you want to put only a value in an object.