在 TypeScript 中将数字转换为字符串 [英] Casting a number to a string in TypeScript

查看:78
本文介绍了在 TypeScript 中将数字转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which is the the best way (if there is one) to cast from number to string in Typescript?

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

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

In this case the compiler throws the error:

类型数字"不可分配给类型字符串"

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

那么哪种方法更好?

推荐答案

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

"Casting" is different than conversion. In this case, window.location.hash will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:

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

如果您不想在 page_numbernullundefined 时抛出错误,这些转换是理想的.而 page_number.toString()page_number.toLocaleString() 将在 page_numbernull 时抛出未定义.

These conversions are ideal if you don't want an error to be thrown when page_number is null or undefined. Whereas page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined.

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

When you only need to cast, not convert, this is how to cast to a string in TypeScript:

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

as string 转换注解告诉 TypeScript 编译器在编译时将 page_number 视为字符串;它不会在运行时转换.

The <string> or as string cast annotations tell the TypeScript compiler to treat page_number as a string at compile time; it doesn't convert at run time.

然而,编译器会抱怨你不能给字符串赋值.您必须首先转换为 ,然后转换为 :

However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>, then to <string>:

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

所以直接转换更容易,它在运行时和编译时处理类型:

So it's easier to just convert, which handles the type at run time and compile time:

window.location.hash = String(page_number); 

(感谢@RuslanPolutsygan 解决了字符串数字转换问题.)

(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)

这篇关于在 TypeScript 中将数字转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆