Typing parsed string using interfaces
The interfaces can also be used to type the parsed string to the required type as shown in the below example.
Example: This example shows the parsing of JSON string using interface.
const jsonStr1 =
'{"name": "w3wiki", "desc": "A Computer Science Portal for Geeks"}';
const jsonStr2 =
'{"name": "Google", "desc": "Searching Platform", "workforce": 2000}';
interface parseInterface {
name: string;
desc: string;
workforce?: number;
}
const parsedStr1: parseInterface =
JSON.parse(jsonStr1);
const parsedStr2: parseInterface =
JSON.parse(jsonStr2);
console.log(`Company Name:
${parsedStr1.name},
Description:
${parsedStr1.desc}`);
console.log(`Company Name:
${parsedStr2.name},
Description: ${parsedStr2.desc},
Work Force: ${parsedStr2.workforce}`);
Output:
Company Name: w3wiki, Description: A Computer Science Portal for Geeks
Company Name: Google, Description: Searching Platform, Work Force: 2000
How to parse JSON string in Typescript?
In this tutorial, we will learn how we can parse a JSON string in TypeScript. The main reason for learning about it is to learn how we can explicitly type the resulting string to a matching type. The JSON.parse() method will be used to parse the JSON string by passing the parsing string as a parameter to it.
Syntax:
JSON.parse(parsingString);
We can type the parsed string with an explicit type using the following methods:
Table of Content
- Typing parsed string using the type alias
- Typing parsed string using interfaces
- Typing parsed array string
- Typing parsed string using classes
Contact Us