在TypeScript中将数字转换为字符串 [英] Casting a number to a string in TypeScript
问题描述
在Typescript中从数字转换为字符串的最佳方法(如果有)?
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:
类型'number'不能分配给'string'类型
Type 'number' is not assignable to type 'string'
因为 location.hash
是一个字符串。
window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function
那么哪种方法更好?
推荐答案
Casting与转换不同。在这种情况下, window.location.hash
会将数字自动转换为字符串。但是为了避免TypeScript编译错误,您可以自己进行字符串转换:
"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);
如果你不希望在 page_number
是 null
或 undefined
。而当 page_number code>是
null
或 undefined
。
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
.
当你只需要转换,而不是转换时,这就是如何在TypeScript中转换为字符串:
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;
< string>
或 as string
cast annotations告诉TypeScript编译器在编译时将 page_number
视为字符串;它不会在运行时转换。
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.
但是,编译器会抱怨您无法为字符串分配数字。您必须首先转换为< any>
,然后转换为< string>
:
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);
(感谢@RuslanPolutsygan捕捉字符串编号问题。)
(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)
这篇关于在TypeScript中将数字转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!