Getter Methods on Deserialized Objects in Typescript

We have a variety of Http calls to our services that return a collection of objects. In our angular application, typescript interprets these into the appropriate type if specified, for example Person:

export class Person{
  public firstName: string;
  public lastName: string;
  public salutation: string;
}

Let's say I want to be able to easily build a greeting string for this user, but I want to be a good programmer and do it once instead of multiple places. So I create a getter that will retrieve it:

export class Person{
  public firstName: string;
  public lastName: string;
  public salutation: string;
  public get greeting(): string {
      return salutation + " " + firstName + " " + lastName;
  }
}

However, when typescript deserialized it, it is missing the prototype of the greeting property (it is set to undefined). I get that typescript is mapping the JSON object to the class it has, and any missing fields/properties do not exist on the mapped object (returning undefined if called). What's the best way to fix this?

As an example of how we are calling the service:

this.authHttp.post(this.url, user, params).then(
  (res: Person) => {
      console.log(res);
      console.log(res.greeting);
  }
);

What you had worked by coincidence because the property names you were accessing were also provided by the response from the .post. In reality, TypeScript is no longer used after the tsc command which transpiles it to JavaScript source. Because of this, you lose all type-checking at runtime.

If you were to hard-code this assignment, like so:

let me: Person = { firstName: 'Ian', lastName: 'MacDonald', salutation: 'Hello.' };

you will receive a TypeScript error as it attempts to create the JavaScript.

Property 'greeting' is missing in type
    '{ firstName: string; lastName: string; salutation: string; }'
    but required in type 'Person'.ts(2741)

The same error will appear for any functions that you have defined on your class, as well. This is because { ... } is not your type; it only has whatever is explicitly defined. What comes down as your server response will be subject to the same assignment rules, but the issue won't be present (because the data isn't present) until run-time.

I recommend using a pipe to construct yourself an instance of your class before anything attempts to use the server response so that any errors can be caught at first contact instead of 10s later when you finally try to access the .save() action that doesn't exist.

.post(...).pipe(map((incoming: any) => {
  let person: Person = new Person();
  person.firstName = incoming.firstName;
  person.lastName = incoming.lastName;
  person.salutation = incoming.salutation;
  return person;
});

Getter Methods on Deserialized Objects in Typescript, In our angular application, typescript interprets these into the appropriate type if specified, for example Person: export class Person{ public firstName: string;  When you pass a plain JavaScript object to a Vue instance as its data option, Vue will walk through all of its properties and convert them to getter/setters using Object.defineProperty. The getter/setters are invisible to the user, but under the hood they enable Vue to perform dependency-tracking and change-notification when properties are

You have to create what's called a copy constructor that takes in all the fields of the object:

constructor(firstName: string, lastName: string) {
    this.firstName = firstName;
    this.lastName = lastName;
}

Now you can do

http.post(...)
    .pipe(map(res => new Person(res.firstName, res.lastName)))
    .subscribe(...);

There's many variants of this, of course. You can just do

constructor(public firstName: string, public lastName: string) {}

to avoid manually assigning the values again, for example. Or think of any other way you'd like to write this. It all comes down to the same, which is that you need to actually create an instance of your class rather than using the class type only as a type.

Expose getters to JSON.stringify by generating a toJSON method , TypeScript Version: All Problem Currently getters are not called when an initialized Typescript object is serialized into JSON. While it is logical  Accessors - getters/setters TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object. Let’s convert a simple class to use get and set.

The response of HTTP calling doesn't generate objects of Person class. The response is at really a plain JavaScript object that obviouslly doesn't have the greeting() method of Person class.

In order to fix that, you can apply the following code:

http.post(...)
    .pipe(map(res => Object.assign(new Person(), res)))
    .subscribe(...);

The Object.assign(new Person(), res) function will copy ALL the values of res to the Person instance. After this map, you will have a real instance of Person with its properties values copy from the resource returned by the http calling.

typestack/class-transformer: Proper decorator-based , Also it allows to serialize / deserialize object based on criteria. Since Typescript does not have good reflection abilities yet, we should implicitly your getter or method return by setting a @Expose() decorator to those getters or methods:. Okay let’s move on. Why don’t we create our own set and get methods to demonstrate how we can use them. ES5 and Object.defineProperty. Taking the above example, why don’t we write our own implementation? First, let’s define a quick module pattern using ES5 (wait for TypeScript later, okay) to encapsulate our small constructor example:

json2typescript, Provides TypeScript methods to map a JSON object to a JavaScript object on runtime. Tip: All serialize() and deserialize() methods may throw an Error in case of failure. Make sure Note the use of public getter and setter. TypeScript Accessor In TypeScript, there are two supported methods getter and setter to access and set the class members. The greater method control over how a member is accessed on each object. Methods of the typescript accessor property:

Jackson-js: Powerful JavaScript decorators to serialize/deserialize , Jackson-js: Powerful JavaScript decorators to serialize/deserialize objects into @JsonProperty() : each class property (or its getter/setter) must be decorated with also because, sometimes, compilers such as TypeScript and Babel, can strip  TypeScript Type Template. Let’s say you created an object literal in JavaScript as − var person = { firstname:"Tom", lastname:"Hanks" }; In case you want to add some value to an object, JavaScript allows you to make the necessary modification. Suppose we need to add a function to the person object later this is the way you can do this.

Package, Therefore, any getters, methods, etc. on the model object being returned will not with the wrong type, which fail silently because of typescript's duck typing. TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object. Let’s convert a simple class to use get and set. First, let’s start with an example without getters and setters.