2

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?

6
  • 1
    For the same reason that if you do var a = 1; var b = a + 1; then b is 2 but a is still 1. Type assertion is something you do to an expression, it does not change the type of an existing variable. Commented Mar 20, 2021 at 14:50
  • TS type assertion only tell the compiler about the type. so it helps developer to use the variable properly. it does not convert the data type. so console log obviously show it is string. Commented Mar 20, 2021 at 15:05
  • To be clear, are you asking why the log shows string at runtime, or are you asking why the variable str doesn't have type number at compile-time? Commented Mar 20, 2021 at 15:15
  • Im actually more confused about type of str2 being String. Can I say that, the type annotations are just ways for the compiler to check if semantics are right, it does not care about what types the underlying values actually are, and won't do anything about it? Commented Mar 20, 2021 at 15:35
  • off-note: str2 is not String - the latter is the boxed object-like value (and corresponding type) that you can get with new String("value here"). Although you will likely not use it, it is important to distinguish between them. Commented Mar 20, 2021 at 16:02

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

I think the question is about types, not values; OP is asking why the variable str doesn't have type number after the type assertion.
Yeah, I explained it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.