Open In App

How to Convert Typescript Dictionary to String ?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, dictionaries are often represented as the objects where keys are associated with the specific values. Converting a TypeScript dictionary to a string is an important task usually when doing API calls where we cast the JSON response from the API to a string.

Below are the ways to convert a TypeScript dictionary to a string:

Using JSON.stringify() method

Since TypeScript is a superset of JavaScript, it also provides the JSON.stringify() method to convert a JavaScript object into a JSON string. It is the easiest and most concise way to convert a TypeScript dictionary to a string.

Syntax

let dictString: string = JSON.stringify(dictionary);

Example: The below code uses JSON.stringify() method to convert the TypeScript dictionary to a string.

Javascript




interface Dictionary{
    [key:string]:string;
}
let dictionary:Dictionary = {
    "name": "geeksforgeeks",
    "desc": "A computer science portal",
    "est": "2009" };
let dictString: string = JSON.stringify(dictionary);
console.log(dictString);


Output:

"{"name":"geeksforgeeks","desc":"A computer science portal","est":"2009"}"

Using a custom function

In this approach, we use the Object.entries() method along with a for-loop to convert a dictionary to a string. The Object.entries() method is used to extract the key-value pairs from an object. Here, we create a custom function to iterate through the key-value pairs of the dictionary and formatting each key-value pair into a string.

Syntax

function dictionaryToString(dictionary: Dictionary): string {
return Object.entries(dictionary)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
}

Example: The below code uses a custom function to convert the TypeScript dictionary to a string.

Javascript




interface Dictionary{
    [key:string]:string;
}
function dictionaryToString(dictionary: Dictionary): string {
  return Object.entries(dictionary)
  .map(([key, value]) => `${key}: ${value}`)
  .join(', ');
}
let dictionary:Dictionary = {
    "name": "geeksforgeeks",
    "desc": "A computer science portal",
    "est": "2009" };
 
let dictString: string =
    dictionaryToString(dictionary);
console.log(dictString);


Output:

"name: geeksforgeeks, desc: A computer science portal, est: 2009" 


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

Similar Reads