简体   繁体   中英

understanding typescript type assertion

I am just going through a TypeScript tutorial and this piece of code makes me confused.

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. Str2 was defined as number. So why str and str2 are not both type number since one is converted to be number and the other is declared number?

TypeScript type assertion does not convert the value of the expression. It only tells the TypeScript compiler to think it is a specific type. When you look at the compiled code, you won't find number anywhere. 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:

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

log: Number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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