Corey Ogburn
Corey Ogburn

Reputation: 24727

Convert vanilla object to class?

I'm building some best practices with TypeScript. If I make a web request and I get a JSON object with properties Name and Age is there an easy way to convert it to my class that has properties Name and Age as well as a function say PrintPerson?

I know I could write up a constructor that takes the object and field by field copies it into this so the class has the same data. Here's a trivial example:

interface RawPerson {
    Name: string;
    Age: number;
}

class Person implements RawPerson {
    Name: string;
    Age: number;

  constructor(obj: RawPerson) {
      this.Name = obj.Name;
      this.Age = obj.Age;
  }

  PrintPerson() {
      console.log(this.Name + ' is ' + this.Age);
  }
}

var json = { Name: 'Corey', Age: 26 };
// What works
new Person(json).PrintPerson();
// Something simple I'd like to do (but doesn't work)
// If this worked, I wouldn't need the Person constructor
(<Person>json).PrintPerson();

TypeScript Playground

Having a constructor copy over every field can get tedious. I'd like to do something simple like cast it and just hope that those functions are magically now there. They aren't. Is there some alternative that would save me from writing this clunky constructor?

Upvotes: 2

Views: 2445

Answers (1)

MartyIX
MartyIX

Reputation: 28646

What about using Object.assign?

interface Object {    
    assign(target: any, ...sources: any[]): any;
}

interface RawPerson {
    Name: string;
    Age: number;
}

class Person implements RawPerson {
    Name: string;
    Age: number;

  constructor(obj: RawPerson) {
      Object.assign(this, obj);
  }

  PrintPerson() {
      console.log(this.Name + ' is ' + this.Age);
  }
}

var json = { Name: 'Corey', Age: 26 };
new Person(json).PrintPerson(); // prints: "Corey is 26"

Upvotes: 8

Related Questions