Casting a number to a string in TypeScript
Asked Answered
B

8

284

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

var page_number:number = 3;
window.location.hash = page_number; 

In this case the compiler throws the error:

Type 'number' is not assignable to type 'string'

Because location.hash is a string.

window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function

So which method is better?

Barmaid answered 13/9, 2015 at 21:15 Comment(0)
T
451

"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:

window.location.hash = ""+page_number; 
window.location.hash = String(page_number); 

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:

window.location.hash = <string>page_number; 
// or 
window.location.hash = page_number as string;

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>:

window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;

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

window.location.hash = String(page_number); 

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

Testosterone answered 16/9, 2015 at 11:43 Comment(4)
Careful, if page_number is null this will set window.location.hash to *the string "null". (I'd prefer an error :D).Leu
If you don't want compiler to complain just say window.location.hash = <any>page_number;Orlando
Using conversion (ie. String(page_number)) rather than casting is necessary when you want to use any String methods, like toLowerCase().Sanctity
Also, you can use template string `${page_number}`Forwent
L
42

Utilize toString() (or toLocaleString(), but take care that it might add things like 1000's separator characters), for example:

var page_number:number = 3;
window.location.hash = page_number.toString();

These throw an error if page_number is null or undefined. If you don't want that you can choose the fix appropriate for your situation:

// Fix 1:
window.location.hash = (page_number || 1).toString();

// Fix 2a:
window.location.hash = !page_number ? "1" page_number.toString();

// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toString();

// Fix 3, modern js:
window.location.hash = page_number?.toString() || "1";
Leu answered 13/9, 2015 at 21:32 Comment(2)
Do not use toLocaleString for large numbers as it adds commas just like a currency. It will destroy identifiers.Milter
I had missed the above comment at the time, but it's very valid and have slipstreamed that info into the answer.Leu
S
16

One can also use the following syntax in typescript. Note the backtick " ` "

window.location.hash = `${page_number}`
Santo answered 22/9, 2018 at 20:57 Comment(2)
It is a javascript feature, not a typescript one. I think it is cleaner to just use String(page_number)Camber
FWIW Typescript HAS overloaded this syntax with template typesLuther
N
12

This is some short ways

any_type = "" + any_type; 
any_type = String(any_type); 
any_type = `${any_type}`;
Nissen answered 4/3, 2021 at 4:31 Comment(0)
T
7

window.location.hash is a string, so do this:

var page_number: number = 3;
window.location.hash = String(page_number); 
Takeo answered 2/7, 2018 at 21:11 Comment(0)
H
4

Easiest way:

var num = 3; var str =`${num}`;

Hebron answered 2/1, 2023 at 14:12 Comment(0)
P
3

Just use: page_number?.toString()

Protuberate answered 20/5, 2022 at 6:0 Comment(0)
V
0

const page_number = 3;

window.location.hash = page_number as string; // Error

"Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first." -> You will get this error if you try to typecast number to string. So, first convert it to unknown and then to string.

window.location.hash = (page_number as unknown) as string; // Correct way

Venomous answered 3/4, 2020 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.