-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?

2
  • Possible duplicate of How do I initialize a typescript object with a JSON object Commented Sep 1, 2017 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) Commented Sep 1, 2017 at 17:28

1 Answer 1

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.

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

6 Comments

This is not valid TypeScript, nor does it answer the question properly (for instance, the date property is not a Date object.)
But lesson is still not an instance of the Lesson class. You need to do something like lesson = new Lesson(), and then start setting properties. And date is still not a Date. Sorry, but this is not a proper answer.
you can also see there, same problem.
You can also use this library npmjs.com/package/serializer.ts
|

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.