TypeScript String toString() Method
The toString() method in TypeScript is a built-in function used to return a string representation of the specified object. This method is particularly useful when you need to convert various types of objects to their string forms.
Syntax
The syntax for using the toString() method is straightforward:
string.toString()
Parameters
- The toString() method does not accept any parameters.
Return Value
- This method returns a string representing the specified object.
Examples of TypeScript String toString() Method
Example 1: Basic Usage of toString() Method
In this example, we will convert a string object to its string representation using the toString() method. Here, the toString() method is called on the platform string, which simply returns the string itself
let platform: string = "Geeksforgeeks - Best Platform";
let result: string = platform.toString();
console.log(result);
Output:
Geeksforgeeks - Best Platform
Example 2: Using toString() on a String Object
In this example, we will use the toString() method on a String object created using the String constructor. Here, description is a String object. The toString() method converts this object to a primitive string.
let description: String = new String("TypeScript - String toString()");
let result: string = description.toString();
console.log(result);
Output:
TypeScript - String toString()