How to useObject Destructuring in JSON
Object destructuring in TypeScript allows you to directly extract properties from an object and assign them to variables. You can use this technique to initialize a TypeScript object with a JSON object.
Example: In this example we parses a JSON string into an object, then extracts username and userAge using object destructuring, logging them.
let jsonString =
'{"username": "GFG", "userAge": 22}';
let { username, userAge } =
JSON.parse(jsonString);
console.log(username);
console.log(userAge);
Output
GFG 22
How to Initialize a TypeScript Object with a JSON-Object ?
To initialize a TypeScript Object with a JSON-Object, we have multiple approaches. In this article, we are going to learn how to initialize a TypeScript Object with a JSON-Object.
Below are the approaches used to initialize a TypeScript Object with a JSON-Object:
Table of Content
- Object.assign
- Type Assertion
- Spread Operator
- Class Initialization
- Using Object Destructuring