How to Cast a JSON Object Inside of TypeScript Class?


In TypeScript, casting JSON objects inside classes can be a useful technique for mapping JSON data to structured TypeScript objects. By explicitly defining the types, we can ensure type safety and access the properties of the JSON object seamlessly. In this tutorial, we will guide you through the process of casting JSON objects inside TypeScript classes, enabling users to leverage the full power of TypeScript's static typing.

Syntax

Users can follow the syntax below to create a cast of a JSON object inside a TypeScript class.

class MyClass {
   // Define class properties
   property1: string;
   property2: number;
   constructor(json: any) {

      // Cast the JSON object to the class type
      const castedJson = json as MyClass;

      // Assign properties from the JSON object
      this.property1 = castedJson.property1;
      this.property2 = castedJson.property2;
   }
}

In the above syntax, we create a class called MyClass with properties property1 of type string and property2 of type number. The constructor takes a parameter json of type any, representing the JSON object.

Inside the constructor, the json object is cast using the keyword, indicating that it should be treated as an instance of MyClass. The properties of castedJson are then assigned to the corresponding properties of the class.

Example 1

In this example, we define the Person class with properties for name, age, and email. The constructor takes a parameter json of type any, representing the JSON object.

After that, we cast the json object as an instance of the Person class using type assertion. The properties of the castedJson object are then assigned to the corresponding properties of the class.

Next, we define a method called displayDetails() within the Person class. This method displays the person's name, age, and email by logging them into the console.

Finally, we create a JSON object called jsonData, representing a person's details. We create an instance of the Person class named person by passing the jsonData to the constructor. We then invoke the displayDetails() method on the person object to access and display the person's details.

// Define the Person class
class Person {
   name: string;
   age: number;
   email: string;
   constructor(json: any) {
      const castedJson = json as Person;
      this.name = castedJson.name;
      this.age = castedJson.age;
      this.email = castedJson.email;
   }

   displayDetails() {
      console.log(`Name: ${this.name}`);
      console.log(`Age: ${this.age}`);
      console.log(`Email: ${this.email}`);
   }
}

// Creating a JSON object representing a person
const jsonData = {
   "name": "John Doe",
   "age": 30,
   "email": "johndoe@example.com"
};

// Creating an instance of the Person class
const person = new Person(jsonData);

// Accessing and displaying the person's details
person.displayDetails();

On compiling, it will generate the following JavaScript code −

// Define the Person class
var Person = /** @class */ (function () {
   function Person(json) {
      var castedJson = json;
      this.name = castedJson.name;
      this.age = castedJson.age;
      this.email = castedJson.email;
   }
   Person.prototype.displayDetails = function () {
      console.log("Name: ".concat(this.name));
      console.log("Age: ".concat(this.age));
      console.log("Email: ".concat(this.email));
   };
   return Person;
}());

// Creating a JSON object representing a person
var jsonData = {
   "name": "John Doe",
   "age": 30,
   "email": "johndoe@example.com"
};

// Creating an instance of the Person class
var person = new Person(jsonData);

// Accessing and displaying the person's details
person.displayDetails();

Output

The above code will produce the following output −

Name: John Doe
Age: 30
Email: johndoe@example.com

Example 2

In this example, we have defined a TypeScript class Employee that represents an employee. The class has properties for name, position, and salary. The constructor takes a parameter json of type any, representing the JSON object.

By casting the json object as an instance of the Employee class using type assertion, we ensure that the JSON object is treated as an employee object.

We also have a method calculateAnnualBonus() that calculates the annual bonus for the employee based on their salary. In this example, we assume a fixed bonus percentage of 10%.

The displayEmployeeSummary() method provides an interactive summary of the employee's details. It showcases the employee's name, position, salary (formatted with proper currency notation), and the calculated annual bonus (also formatted with proper currency notation).

We then create a JSON object named jsonData that represents an employee's details.

By creating an instance of the Employee class called an employee and passing the jsonData to the constructor, we cast the JSON object into the Employee class.

Finally, we invoke the displayEmployeeSummary() method on the employee object to access and display the employee's summary.

class Employee {
   name: string;
   position: string;
   salary: number;
   constructor(json: any) {
      const castedJson = json as Employee;

      this.name = castedJson.name;
      this.position = castedJson.position;
      this.salary = castedJson.salary;
   }
   calculateAnnualBonus(): number {
      const bonusPercentage = 0.1; // 10% bonus
      const bonusAmount = this.salary * bonusPercentage;
      return bonusAmount;
   }
   displayEmployeeSummary() {
      console.log(`Name: ${this.name}`);
      console.log(`Position: ${this.position}`);
      console.log(`Salary: $${this.salary.toLocaleString()}`);
      console.log(`Annual Bonus: $${this.calculateAnnualBonus().toLocaleString()}`);
   }
}

// Creating a JSON object representing an employee
const jsonData = {
   "name": "John Smith",
   "position": "Senior Developer",
   "salary": 80000
};

// Creating an instance of the Employee class
const employee = new Employee(jsonData);
 
// Displaying the employee summary
employee.displayEmployeeSummary();

On compiling, it will generate the following JavaScript code −

var Employee = /** @class */ (function () {
   function Employee(json) {
      var castedJson = json;
      this.name = castedJson.name;
      this.position = castedJson.position;
      this.salary = castedJson.salary;
   }
   Employee.prototype.calculateAnnualBonus = function () {
      var bonusPercentage = 0.1; // 10% bonus
      var bonusAmount = this.salary * bonusPercentage;
      return bonusAmount;
   };
   Employee.prototype.displayEmployeeSummary = function () {
      console.log("Name: ".concat(this.name));
      console.log("Position: ".concat(this.position));
      console.log("Salary: $".concat(this.salary.toLocaleString()));
      console.log("Annual Bonus: $".concat(this.calculateAnnualBonus().toLocaleString()));
   };
   return Employee;
}());

// Creating a JSON object representing an employee
var jsonData = {
   "name": "John Smith",
   "position": "Senior Developer",
   "salary": 80000
};

// Creating an instance of the Employee class
var employee = new Employee(jsonData);

// Displaying the employee summary
employee.displayEmployeeSummary();

Output

The above code will produce the following output −

Name: John Smith
Position: Senior Developer
Salary: $80,000
Annual Bonus: $8,000

Through this tutorial, users have learned how to cast JSON objects inside TypeScript classes. By utilizing type assertion, users can ensure type safety and seamlessly map JSON data to structured TypeScript objects. This technique is valuable when dealing with JSON-based APIs or when working with data that needs to be strongly typed within TypeScript projects.

Updated on: 31-Aug-2023

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements