Typing parsed array string
An array string can also be parsed using the parse method and required to be typed as an explicit array of required types.
Syntax:
const parsedString = JSON.parse(string) as createdType[];
Example: The below example will explain how to type an parsed array string.
const jsonStr =
`[
{"name": "w3wiki", "desc": "A Computer Science Portal for Geeks"},
{"name": "Google", "desc": "Searching Platform", "workforce": 2000}
]`;
type parsedType = {
name: string,
desc: string,
workforce?: number
}
const parsedStr = JSON.parse(jsonStr) as parsedType[];
console.log(`Company Name:
${parsedStr[0].name},
Description:
${parsedStr[0].desc}`);
console.log(`Company Name:
${parsedStr[1].name},
Description:
${parsedStr[1].desc}`);
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