Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.
Just use JSON.stringify(object). It's built into Javascript and can therefore also be used within Typescript.
TS gets compiled to JS which then executed. Therefore you have access to all of the objects in the JS runtime. One of those objects is the JSON object. This contains the following methods:
JSON.parse()method parses a JSON string, constructing the JavaScript value or object described by the string.JSON.stringify()method converts a JavaScript object or value to a JSON string.
Example:
const jsonString = '{"employee":{ "name":"John", "age":30, "city":"New York" }}';
const JSobj = JSON.parse(jsonString);
console.log(JSobj);
console.log(typeof JSobj);
const JSON_string = JSON.stringify(JSobj);
console.log(JSON_string);
console.log(typeof JSON_string);
javascript - Typescript and converting Object to String - Stack Overflow
javascript - Converting an object to a string - Stack Overflow
In JavaScript, object keys/properties are strings?
How to convert an interface/class property (key) into a string?
I would recommend using JSON.stringify, which converts the set of the variables in the object to a JSON string.
var obj = {
name: 'myObj'
};
JSON.stringify(obj);
Most modern browsers support this method natively, but for those that don't, you can include a JS version.
Use javascript String() function
String(yourobject); //returns [object Object]
or stringify()
JSON.stringify(yourobject)
I just learned that you can give this type to JavaScript objects:
const styleObject: Record<string, string> = {
color: 'red',
fontSize: '14px'
};
As you can see, the color and fontSize keys/property names aren't strings (they aren't surrounded by quotes)—so how come TypeScript is okay with treating them as strings?