In TypeScript, casting and conversion are two different concepts. Here’s the situation you’re dealing with:
You have:
var page_number: number = 3;
window.location.hash = page_number;
And since window.location.hash
expects a string, TypeScript complains when you pass a number. To handle this properly, we need to convert the number to a string.
You have two common ways to convert the number to a string:
window.location.hash = "" + page_number; // using an empty string
window.location.hash = String(page_number); // using the String() function
Both methods work and handle runtime conversions. If page_number
were null
or undefined
, they’d safely convert it without throwing errors.
However, page_number.toString()
or page_number.toLocaleString()
would fail in the case of null
or undefined
, so it’s safer to use the two above methods in more dynamic cases.
If you’re interested in casting (though it’s generally less recommended), you could do:
window.location.hash = <string>page_number;
// or
window.location.hash = page_number as string;
But this doesn’t perform an actual conversion at runtime. TypeScript will still throw an error because you can’t assign a number to a string directly. To bypass this, you’d need a two-step cast, first to any
and then to string
:
window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
In most cases, the best approach is String(page_number)
because it safely converts both at runtime and satisfies TypeScript’s type-checking.