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

Ma *_*rez 141 javascript casting typescript

哪些是在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)

那么哪种方法更好?

Rob*_*ner 249

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

window.location.hash = ""+page_number; 
window.location.hash = String(page_number); 
Run Code Online (Sandbox Code Playgroud)

这些转换是理想的,如果你不想被抛出一个错误,当page_numbernullundefined.而page_number.toString()page_number.toLocaleString()操作时将抛出page_numbernullundefined.

当你只需要转换,而不是转换时,这就是如何在TypeScript中转换为字符串:

window.location.hash = <string>page_number; 
// or 
window.location.hash = page_number as string;
Run Code Online (Sandbox Code Playgroud)

<string>as string投注解告诉打字稿编译器把page_number在编译时间的字符串; 它不会在运行时转换.

但是,编译器会抱怨您无法为字符串分配数字.你必须首先施放<any>,然后<string>:

window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;
Run Code Online (Sandbox Code Playgroud)

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

window.location.hash = String(page_number); 
Run Code Online (Sandbox Code Playgroud)

(感谢@RuslanPolutsygan捕获字符串数字转换问题.)

  • 小心,如果`page_number` 是`null`,这会将`window.location.hash` 设置为*字符串`"null"`。(我更喜欢错误:D)。 (2认同)
  • 当你想使用任何 `String` 方法时,使用 **conversion**(即 `String(page_number)`)而不是 *casting* 是必要的,比如 `toLowerCase()`。 (2认同)

Jer*_*oen 29

只是利用toString或者toLocaleString我会说.所以:

var page_number:number = 3;
window.location.hash = page_number.toLocaleString();
Run Code Online (Sandbox Code Playgroud)

如果page_numbernull或,则抛出错误undefined.如果您不希望这样,您可以选择适合您情况的修复:

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

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

// Fix 2b (allows page_number to be zero):
window.location.hash = (page_number !== 0 && !page_number) ? "1" page_number.toLocaleString();
Run Code Online (Sandbox Code Playgroud)

  • 不要对大数字使用 toLocaleString,因为它会像货币一样添加逗号。它将破坏标识符。 (3认同)

Neh*_*nia 13

还可以在打字稿中使用以下语法。注意反引号“`”

window.location.hash = `${page_number}`
Run Code Online (Sandbox Code Playgroud)


Bin*_* Ho 11

这是一些简短的方法

any_type = "" + any_type; 
any_type = String(any_type); 
any_type = `${any_type}`;
Run Code Online (Sandbox Code Playgroud)


ran*_*shu 6

window.location.hash 是一个string,所以这样做:

var page_number: number = 3;
window.location.hash = String(page_number); 
Run Code Online (Sandbox Code Playgroud)