Umar Adkhamov
Umar Adkhamov

Reputation: 37

unknown type given number but casted as string acts as a number

I have the following code.

let myVar = unknown;
myVar = 5;
console.log((myVar as string) + 5);

This code's output is 10. However, when we add string and number it should concatenate two. In this particular scenario I thought I would get 55; Could someone clear my misunderstanding?

Upvotes: 0

Views: 813

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187134

Typescript compiles to javascript, javascript does not have types. So your code compiles to:

let myVar;
myVar = 5;
console.log(myVar + 5);

And 5 + 5 is 10.

You assign a number, then add a number to that, and you get back a number.


unknown is a type that accepts any value, but can't be narrowed to a more specific type until you assert or validate it as something. This process does not change the value, just the typescript compilers understanding of the type.

There are two ways to get something useful from unknown.

You can test the value like:

if (typeof myVar === 'number') myVar // myVar is number here
if (typeof myVar === 'string') myVar // myVar is string here

Or you can use a type assertion to override the compiler with as, which is what you did in your example. Doing this provides no type safety, and should be avoided.

Upvotes: 3

Related Questions