Home > database >  React Typescript. What is difference between 'as number' and 'Number()'?
React Typescript. What is difference between 'as number' and 'Number()'?

Time:11-28

I believed that 'strVariable as number' converts strVariable to a number type.
But being struggled for few hours, I found out it's type is not being changed.
Number(strVariable) was the key.

What is the difference between 'as number' and 'Number()'?
And if 'as number' doesn't actually converts the type to number, why is the type error of IDE being removed ??

const strVariable: string = '';
const numVariable: number = 0;
numVariable = strVariable as unknown as number; // I thought it is converting to number but it wasn't
typeof (strVariable as unknown as number); // string. but type error is gone. How?
typeof (Number(strVariable)) // it do converts to number.

CodePudding user response:

Okay so in order to understand that we first need to clarify that the type system TypeScript gives us does not exist on runtime. You can look at it like you have 2 completely different layers of types on variables, one being the type you expect it to be - some sort of a virtual type (the TypeScript type), and the other one being the type it actually is on runtime (the JavaScript type).

The typeof keyword gives you the runtime type of a variable while the as keyword changes the TypeScript type of the variable.

Now that we understand that, we can look at your specific situation. You are using the as keyword which belongs to TypeScript and performs a "virtual" cast. When using it, you are telling the typescript compiler that you are expecting the variable to be a number even though it might not actually be a number. When using the typeof keyword you are getting the runtime type of the variable, and because you only used the as keyword and didn't really converted it, it stayed the same.

On the other example, where you used the Number() function, you actually converted the variable on the JavaScript runtime which means that the actual type of the variable changed to being a number which means that when you check the type using the typeof keyword you will get number as the type of the variable.

Hope this was clear enough, if not maybe this article about type casting in TypeScript will help clarify things: https://dev.to/ylerjen/typescript-cast-is-a-type-breaker-1jbh

CodePudding user response:

as keyword simply "tell to compiler that is a number". It NOT convert anything, the value MUST be a alredy number, or you incur into unusual behaviors.

Number() is a function, with precise behavior, that can convert same kind of values into a number.

Es:

const n: any = 5;
const s: string = "5";

const a = n as number // <- ok... the type of a was "any", but the content is alredy a number.
const b = s as number // <- error
const c = Number(n) // <- ok!
const d = Number(s) // <- ok, Number() can convert a string onto a number
  • Related