在 Typescript 中从数字转换为字符串的最佳方法是什么(如果有的话)?
var page_number:number = 3;
window.location.hash = page_number;
在这种情况下,编译器会抛出错误:
类型“数字”不可分配给类型“字符串”
因为 location.hash
是一个字符串。
window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function
那么哪种方法更好呢?
原文由 Ma Jerez 发布,翻译遵循 CC BY-SA 4.0 许可协议
“铸造”不同于转换。在这种情况下,
window.location.hash
将自动将数字转换为字符串。但是为了避免 TypeScript 编译错误,您可以自己进行字符串转换:如果您不想在
page_number
是null
或undefined
时抛出错误,那么这些转换是理想的。page_number.toString()
andpage_number.toLocaleString()
will throw whenpage_number
isnull
orundefined
.当您只需要转换而不是转换时,这是在 TypeScript 中转换为字符串的方法:
<string>
或as string
注解告诉 TypeScript 编译器在编译时将page_number
视为字符串;它不会在运行时转换。但是,编译器会抱怨您不能为字符串分配数字。您必须先转换为
<any>
,然后转换为<string>
:所以转换更容易,它在运行时和编译时处理类型:
(感谢@RuslanPolutsygan 发现了字符串数字转换问题。)