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

这是最好的方式(如果有一个)从数字转换到字符串在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

那么哪种方法更好呢?

476293 次浏览

使用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();

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

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

如果您不希望在page_numbernullundefined时抛出错误,则这些转换是理想的。而当page_numbernullundefined时,page_number.toString()page_number.toLocaleString()将抛出。

当你只需要强制转换而不需要转换时,下面是如何在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捕获字符串数字转换问题。)

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

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

还可以在typescript中使用以下语法。注意后面的“'”

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

Const page_number = 3;

Window.location.hash = page_number作为字符串;/ /错误

将“数字”类型转换为“字符串”类型可能是错误的,因为两种类型都没有充分重叠。如果这是故意的,请先将表达式转换为“unknown”。→如果尝试将数字类型转换为字符串,则会得到此错误。首先转换为unknown,然后转换为string。

Window.location.hash = (page_number as unknown) as string;//正确方式

这是一条很短的路

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

只需使用:page_number?.toString()