How to convert any to string in typescript

How to convert any to string in typescript:

We have to use any type in many cases in TypeScript. For example, if we are getting data from a server or any third-party module, and we are not sure what type of value we are getting, we can use any.

But if we need only string types, we need to convert this any type to string. We have two different ways in TypeScript to convert any to string. Let’s have a look:

Method 1: Using toString():

toString converts a value to string. We can use it to convert a value to string. The below example shows how we can use toString with different types of data:

function getStringValue(value: any): string {
    return value.toString();
}


console.log(getStringValue(19));
console.log(getStringValue(19.4890));
console.log(getStringValue('hello'));
console.log(getStringValue(true));

It will print the below output:

"19" 
"19.489" 
"hello" 
"true"

But, note that it will not work with undefined. For undefined, it will throw an error.

Method 2: Using String():

Using the string constructor, we can convert any to string. Let me re-write the same program with String:

function getStringValue(value: any): string {
    return String(value);
}


console.log(getStringValue(19));
console.log(getStringValue(19.4890));
console.log(getStringValue('hello'));
console.log(getStringValue(true));
console.log(getStringValue(undefined));

It will give the below output:

"19" 
"19.489" 
"hello" 
"true" 
"undefined"

It works with undefined as well.

You might also like: