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?
var a = 1; var b = a + 1;thenbis 2 butais still 1. Type assertion is something you do to an expression, it does not change the type of an existing variable.stringat runtime, or are you asking why the variablestrdoesn't have typenumberat compile-time?str2is notString- the latter is the boxed object-like value (and corresponding type) that you can get withnew String("value here"). Although you will likely not use it, it is important to distinguish between them.