在 TypeScript 中将数字转换为字符串

新手上路,请多包涵

在 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 许可协议

阅读 1k
2 个回答

“铸造”不同于转换。在这种情况下, window.location.hash 将自动将数字转换为字符串。但是为了避免 TypeScript 编译错误,您可以自己进行字符串转换:

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

如果您不想在 page_numbernullundefined 时抛出错误,那么这些转换是理想的。 page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined .

当您只需要转换而不是转换时,这是在 TypeScript 中转换为字符串的方法:

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

<string>as string 注解告诉 TypeScript 编译器在编译时将 page_number 视为字符串;它不会在运行时转换。

但是,编译器会抱怨您不能为字符串分配数字。您必须先转换为 <any> ,然后转换为 <string>

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

所以转换更容易,它在运行时和编译时处理类型:

 window.location.hash = String(page_number);

(感谢@RuslanPolutsygan 发现了字符串数字转换问题。)

原文由 Robert Penner 发布,翻译遵循 CC BY-SA 3.0 许可协议

只需使用: page_number?.toString()

原文由 saran3h 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题