Skip to content
Advertisement

Casting a number to a string in TypeScript

Which is the the best way (if there is one) to cast from number to string in Typescript?

JavaScript

In this case the compiler throws the error:

Type ‘number’ is not assignable to type ‘string’

Because location.hash is a string.

JavaScript

So which method is better?

Advertisement

Answer

“Casting” is different than conversion. In this case, window.location.hash will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:

JavaScript

These conversions are ideal if you don’t want an error to be thrown when page_number is null or undefined. Whereas page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined.

When you only need to cast, not convert, this is how to cast to a string in TypeScript:

JavaScript

The <string> or as string cast annotations tell the TypeScript compiler to treat page_number as a string at compile time; it doesn’t convert at run time.

However, the compiler will complain that you can’t assign a number to a string. You would have to first cast to <any>, then to <string>:

JavaScript

So it’s easier to just convert, which handles the type at run time and compile time:

JavaScript

(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement