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

277

在TypeScript中,从数字到字符串的转换(如果有)哪种方法是最好的?

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

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

类型“number”不能赋值给类型“string”

因为location.hash是一个字符串。

window.location.hash = ""+page_number; //casting using "" literal
window.location.hash = String(number); //casting creating using the String() function

那么哪种方法更好呢?

8个回答

444

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

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

如果您不希望在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;

<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指出了字符串-数字转换问题。)


4
注意,如果page_numbernull,这将会把window.location.hash设置为字符串"null"。(我希望出现一个错误:D) - Jeroen
如果你不想让编译器抱怨,只需说window.location.hash = <any>page_number; - Mouneer
2
在想要使用任何String方法,例如toLowerCase()时,使用转换(即String(page_number))而不是强制类型转换是必要的。 - EricRobertBrewer
另外,您可以使用模板字符串 \${page_number}``。 - Ollie

40

使用toString()toLocaleString(),例如:

var page_number:number = 3;
window.location.hash = page_number.toLocaleString();

如果page_numbernullundefined时,会抛出错误。 如果您不希望出现这种情况,可以选择适合您情况的修复方法:

// 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();

3
不要使用toLocaleString来处理大数字,因为它会像货币一样添加逗号,这会破坏标识符。 - Obaid

16

在TypeScript中,也可以使用以下语法。请注意反引号 " ` "。

window.location.hash = `${page_number}`

这是一个 JavaScript 特性,而不是 TypeScript 特性。我认为直接使用 String(page_number) 更加简洁。 - Ambrus Tóth
顺便提一下,TypeScript已经使用模板类型重载了这个语法。 - Devin Rhode

11

这是一些简短的方法

any_type = "" + any_type; 
any_type = String(any_type); 
any_type = `${any_type}`;

7

window.location.hash是一个字符串,因此需要这样做:

var page_number: number = 3;
window.location.hash = String(page_number); 

3
只需使用:page_number?.toString()

3
最简单的方法是: var num = 3; var str =`${num}`;

0
const page_number = 3; window.location.hash = page_number as string; // 错误
"将类型 'number' 转换为类型 'string' 可能是一个错误,因为两种类型都不足以重叠。如果这是有意的,请先将表达式转换为 'unknown'。" -> 如果您尝试将数字强制转换为字符串,则会出现此错误。因此,首先将其转换为 unknown,然后再转换为字符串。
window.location.hash = (page_number as unknown) as string; // 正确的方式

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接