Open In App

How to Cast a JSON Object Inside of TypeScript Class ?

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.

Example:



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.



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.

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.

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.


Article Tags :