ryan
ryan

Reputation: 43

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?

Upvotes: 2

Views: 1576

Answers (1)

blaumeise20
blaumeise20

Reputation: 2220

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

Upvotes: 2

Related Questions