How to convert object of any type values, to object of string values (Typescript)?

How to convert object of any type values, to object of string values (Typescript)

You can write a function that takes an object as an argument and returns a new object with the same keys and the values converted to strings. Here’s an example:

function convertToString(obj: any): {[key: string]: string} {
  const result: {[key: string]: string} = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      result[key] = obj[key].toString();
    }
  }
  return result;
}

You can then use this function like this:

const obj = {
  a: 1,
  b: true,
  c: [1, 2, 3],
};
const str = convertToString(obj);
console.log(str); // { a: '1', b: 'true', c: '1,2,3' }

This function converts the values of the input object to strings using the toString() method. If you want to use a different method for conversion, you can modify the function accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *