哪些是在Typescript中从数字转换为字符串的最佳方式(如果有的话)?
var page_number:number = 3;
window.location.hash = page_number;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,编译器会抛出错误:
类型'number'不能分配给'string'类型
因为location.hash是一个字符串.
window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function
Run Code Online (Sandbox Code Playgroud)
那么哪种方法更好?
是否可以在 Javascript赋值的左侧使用可选的链接运算符=?
const building = {}
building?.floor?.apartment?.number = 3; // Is this possible?
Run Code Online (Sandbox Code Playgroud)