gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 02:37:53 29 4
gpt4 key购买 nike

在 Typescript 中从数字转换为字符串的最佳方法是什么(如果有的话)?

var page_number:number = 3;
window.location.hash = page_number;

在这种情况下,编译器会抛出错误:

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

那么哪种方法更好呢?

最佳答案

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

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

如果您不希望在 page_number 时抛出错误,这些转换是理想的选择是nullundefined .鉴于 page_number.toString()page_number.toLocaleString()将在 page_number 时抛出是nullundefined .

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

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

<string>as string cast 注释告诉 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 发现了字符串数字转换问题。)

关于javascript - 在 TypeScript 中将数字转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32554624/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com