简体   繁体   English

理解 typescript 类型断言

[英]understanding typescript type assertion

I am just going through a TypeScript tutorial and this piece of code makes me confused.我只是通过 TypeScript 教程,这段代码让我感到困惑。

var str = '1' 
var str2:number = <number> <any> str   //str is now of type number 
console.log(typeof(str2))

log: String

As far as I understand, str was inferred as String in the first place, then it was asserted to be number while assigning it to str2.据我了解,str首先被推断为String,然后在将其分配给str2时将其断言为数字。 Str2 was defined as number. Str2 被定义为数字。 So why str and str2 are not both type number since one is converted to be number and the other is declared number?那么为什么 str 和 str2 不都是数字类型,因为一个被转换为数字而另一个被声明为数字?

TypeScript type assertion does not convert the value of the expression. TypeScript 类型断言转换表达式的 It only tells the TypeScript compiler to think it is a specific type.它只告诉 TypeScript 编译器认为它是特定类型。 When you look at the compiled code, you won't find number anywhere.当您查看编译后的代码时,您不会在任何地方找到number That is the reason why it doesn't behave as you expect.这就是为什么它的行为不像你期望的那样。 If you want to convert the value to a number, you have to use the parseInt function:如果要将值转换为数字,则必须使用parseInt function:

var str = '1' 
var str2:number = parseInt(str)   //str value is now a number 
console.log(typeof(str2))

log: Number

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM