Open In App

How to Cast a JSON Object Inside of TypeScript Class ?

Last Updated : 03 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We use JSON objects to store and transport data between a server and a client application, or locally in a node project. In Typescript, there are two types of objects.

  • Plain objects: When we try to parse JSON data using JSON.parse() method then we get a plain object and not a class object.
  • Class(constructor) objects: A class object is an instance of a Typescript class with own defined properties, constructors and methods.

Example:

  • Data 1: Suppose, we have a Typescript class defined in the client-side:




    class Todo {
        userId: number;
        id: number;
        title: string;
        done: boolean;
       
        getTitle() {
            return this.title;
        }
       
        isDone() {
            return this.done;
        }
    }

    
    

  • Data 2: We have a JSON object stored locally in our project:




    {
        "userId": 1,
        "id": 1,
        "title": "Add Info about the new project",
        "done": true
    }

    
    

The above JSON object can be sent by a server to a web page or any other client-side application. If we clearly observe, the structure of the JSON object is equivalent to that of the Typescript class, but what if we want to access the methods of the Todo class for the JSON object! There are two ways we can accomplish this task, using the assign method of Object class, which essentially clones the JSON object to Todo class object. Another, is using the class-transformer tool which is used to transform Typescript objects into class objects.

Method 1: First, we will have to import the JSON object in our TypeScript file which can be done by using the import keyword in TypeScript, which will load the JSON object into a TypeScript variable. In my case, we have stored the JSON file in the same directory as that of my TypeScript file. Then, we can just use the Object.assign() the method, which will return a Todo class object and we can access methods defined in the Todo class.

  • Program 1:




    import jsonObhect from './todo.json';
       
    // Defining our Todo class
    class Todo {
        userId: number;
        id: number;
        title: string;
        done: boolean;
       
        getTitle() {
            return this.title;
        }
       
        isDone() {
                return this.done;
        }
    }
       
    // Object.assign() will clone jsonData into
    // Todo class object Storing the new class
    // object in a typescript variable
    let newTodo = Object.assign(new Todo(), jsonData);
       
    // Logging the output onto the console
    console.log(newTodo);
    console.log(newTodo.getTitle());

    
    

  • Output:
    Todo {
      userId: 1,
      id: 1,
      title: 'Add Info about new project',
      done: true
    }
    Add Info about new project
    

Method 2: Method one discussed here is easy and useful for simple JSON objects but things can go wrong if we have an object with a complex hierarchy or an array of complex JSON objects. We can use the class-transformer tool for this purpose, It can be easily installed in your local system or node-project using the Node Package Manager. In your local system, use the terminal or command window (depending on your operating system) to execute the following command.

  • Command: The -g flag is used for global install. We will use the plainToClass method of the class-transformer tool to convert our JSON object to a TypeScript class object.
    npm install -g class-transformer

This method will take two parameters, the first parameter will be an instance of the Todo class and the second parameter is the JSON object imported from our local project. First, we will have to import the method from the class-transformer tool in our TypeScript file, so that TypeScript knows which method to use. Again, we have stored my JSON file in the same directory as that of my TypeScript file.

  • Program:




    import jsonObhect from './todo.json';
    import { plainToClass } from "class-transformer";
       
    // Defining our Todo class
    class Todo {
        userId: number;
        id: number;
        title: string;
        done: boolean;
       
        getTitle() {
            return this.title;
        }
       
        isDone() {
            return this.done;
        }
    }
       
    // plainToClass method will convert
    // JSON data to Todo class object
    // Storing the new class object in
    // a typescript variable
    let newTodo = plainToClass(Todo, jsonData);
       
    // Logging the output to the console
    console.log(newTodo);
    console.log(newTodo.isDone());

    
    

  • Output:
    Todo {
      userId: 1,
      id: 1,
      title: 'Add Info about new project',
      done: true
    }
    true
    

Note: Another useful tool that we can use to convert JSON data to TypeScript interfaces is json2ts. If we test this tool for the above JSON object we will get the below TypeScript interface.

declare module namespace {

    export interface RootObject {
        userId: number;
        id: number;
        title: string;
        done: boolean;
    }

}

Then you use the generated interface to define the syntax that you want your typescript class to follow.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads