Langley Langley - 5 years ago 1368
Javascript Question

Correct way to cast a JSON object into a typescript typed variable using a class?

This is a more simple example of what I'm trying to do:

export class Person{

export class PersonForm{

// This line:
default:Person = {name: "Guy"};
// Gives the following error:
// Error:(25, 5) TS2322: Type '{ name: string; }' is not assignable to type 'Person'.
// Property 'id' is missing in type '{ name: string; }'.

// I tried <Person>{name: "Guy"} but it gives the same error.


How can I make the compiler ignore this issue as long as Im not using non existant properties, or how do I declare the class so I can do the assignment this way instead of new Person() and then setting just the properties I want.

Note: Sending an object with all the properties into the constructor is not the solution I'm expecting. Also using an interface works because I can declare the fields optional, how can I do the same in a class?

Adding some more info:

The main goal of what I'm trying to achieve:

Find the best way to declare a class (not an interface) so I can to initialize it with clean code in one line setting only the parameters I want to set. In Java you would overload constructors or use the Builder pattern.

I could certainly try the builder pattern but I'm looking for a more typescript way to do it, if there's any.

Answer Source

Thanks to toskv comments and this question: Constructor overload in TypeScript

I've come up with what I believe is the correct way to do it:

export class PersonForm{

        public name?:string,
        public id?:number){

    default1:Person = new PersonForm();
    default2:Person = new PersonForm("Cool Name");
    default3:Person = new PersonForm("Cool Name", 123 );


By declaring all properties optional in the constructor implementation and overloading constructor definitions you can achieve what I was trying to achieve using a class and not having to send one entire object in the constructor, avoiding to have to build the object yourself.

Still has its perks as you will need a specific order on the parameters, but it's the best I could find. Also I didn't like the fact that I have to overload it with the same paramenters the implementation has in order to use that definition, why would I need to repeat myself?

Again, in this example yes, the best solution would be to use an interface instead, but like I mentioned before, this is not the real example (where I do need a class), just a minor version of it without the code unrelated to what I am trying to achieve.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download