How to cast a JSON object inside of the TypeScript class

JSON is the standard means of communication between systems, whether it be between front-end and back-end or between microservices.

We generally tend to map this JSON data to TypeScript plain objects or interfaces, but sometimes we may need to map this data to a particular TypeScript class.

We have two methods to achieve this:

  • Use the Object.assign() method
  • Use the class-transformer package

Using the Object.assign() method

The Object.assign() method creates a new class object from JSON data and a given class.

Code

index.ts
user.json
import * as userData from './user.json';
// User class
class User {
firstname: string;
lastname: string;
age: number;
//returns fullname
getFullname() {
return this.firstname + " " + this.lastname;
}
//returns age
getAge() {
return this.age;
}
}
//Object.assign method will create a new User class mapping the data userData
let user1 = (<any>Object).assign(new User(), userData)
//printing the full name
console.log(user1.getFullname())

Explanation

In this example:

  • We import the user data from the user.json file.

  • We define our User class, which has firstname, lastname, and age as member variables and getFullname(), getAge() as methods.

  • In line 22, we create a new User class object user1 from userData with the Object.assign() method, in which we pass a User class object new User() and userData as parameters.

  • Line 25 is the proof that we get data from the User class object user1. Here, we print the full name of the user using the getFullName() method provided by the User class.

Using the class-transformer package

Pre-requisite

Install the class-transformer package from your package manager with npm.

npm install class-transformer

Code

index.ts
user.json
import * as userData from './user.json';
import { plainToClass } from "class-transformer";
// User class
class User {
firstname: string;
lastname: string;
age: number;
//returns fullname
getFullname() {
return this.firstname + " " + this.lastname;
}
//returns age
getAge() {
return this.age;
}
}
//plainToClass transforms json data to provided class
let user1 = plainToClass(User, userData);
// printing the user1 class object
console.log(user1);
//priting the full name to console
console.log(user1.getFullname());

Explanation

In this example, we create the data and user class as explained above. The only difference is that we also create a user1 object.

class-transformer comes with a function called plainToClass, which transforms the user JSON data into the User class object user1.

Free Resources