New Number() VS Number()

new Number() vs Number()

Boolean(expression) will simply convert the expression into a boolean primitive value, while new Boolean(expression) will create a wrapper object around the converted boolean value.

The difference can be seen with this:

// Note I'm using strict-equals
new Boolean("true") === true; // false
Boolean("true") === true; // true

And also with this (thanks @hobbs):

typeof new Boolean("true"); // "object"
typeof Boolean("true"); // "boolean"

Note: While the wrapper object will get converted to the primitive automatically when necessary (and vice versa), there is only one case I can think of where you would want to use new Boolean, or any of the other wrappers for primitives - if you want to attach properties to a single value. E.g:

var b = new Boolean(true);
b.relatedMessage = "this should be true initially";
alert(b.relatedMessage); // will work

var b = true;
b.relatedMessage = "this should be true initially";
alert(b.relatedMessage); // undefined

Number() vs new Number()?

Number() by itself returns a number primitive. When you call new Number() you receive a new instance of an Object which represents Number's (relevant ES5 spec).

When you call a property on a primitive, the primitive is auto-boxed (like in Java) to an instance of that object, which is what lets you call helloWorld() on either the object or number.

However, try this;

var x = Number(5);
x.bar = function (x) { alert(x); };
x.bar("hello");

var y = new Number(5);
y.bar = function (x) { alert(x); };
y.bar("hello");

You'll see the latter works whilst the former does not; in the first, the number is autoboxed to a number, and the bar method is added to it (the object). When you call x.bar() you're creating a new auto-boxed Number, which bar doesn't exist on.

In the latter, you're adding a bar method to that Number instance, which behaves like any other Object instance, and therefore it persists throughout the lifetime of the object.

What is the difference between number and Number in TypeScript?

number is only a TypeScript thing - it's a primitive type referring to, well, a number.

But, judging by the error message, it seems that number isn't actually a discrete value like Number.

Indeed - it's a type, so it doesn't exist in emitted code.

a discrete value like Number. On the other hand, user-defined types like classes appear to be discrete values (as they also print the standard function description).

Yes. Classes, of which Number is one, are special. They do two things, somewhat unintuitively:

  • They create a JavaScript class (usable in emitted code)
  • They also create an interface for the class (only used by TypeScript)

If you use Number in a place where a type is expected, TypeScript will not complain, because Number is an interface.

If you use Number in a place where a value (something that exists in emitted code) is expected, TypeScript will not complain, because Number is also a global constructor.

In other words, the two Numbers below refer to completely different things:

// refer to the TypeScript Number interface
let foo: Number;

// refer to the JavaScript global.Number constructor
const someNum = Number(someString);

Using Number in TypeScript is very odd, since it'd, strictly, speaking, refer to a number created via new:

const theNum = new Number(6);

Which there's almost never a reason to do. Use a plain primitive number instead, without an object wrapper.

const theNum = 6;
// theNum is typed as `number`

What is the difference between parseInt() and Number()?

Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:

// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2

// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation

Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.

The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:

Number("010");         // 10
Number("0o10") // 8, explicit octal

parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used

And it can handle numbers in hexadecimal notation, just like parseInt:

Number("0xF");   // 15
parseInt("0xF"); //15

In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:

+"2e1";   // 20
+"0xF"; // 15
+"010"; // 10

Typescript primitive types: any difference between the types number and Number (is TSC case-insensitive)?

JavaScript has the notion of primitive types (number, string, etc) and object types (Number, String, etc, which are manifest at runtime). TypeScript types number and Number refer to them, respectively. JavaScript will usually coerce an object type to its primitive equivalent, or vice versa:

var x = new Number(34);
> undefined
x
> Number {}
x + 1
> 35

The TypeScript type system rules deal with this (spec section 3.7) like this:

For purposes of determining subtype, supertype, and assignment
compatibility relationships, the Number, Boolean, and String primitive
types are treated as object types with the same properties as the
‘Number’, ‘Boolean’, and ‘String’ interfaces respectively.

What is the difference between Unary Plus/Number(x) and parseFloat(x)?

The difference between parseFloat and Number

parseFloat/parseInt is for parsing a string, while Number/+ is for coercing a value to a number. They behave differently. But first let's look at where they behave the same:

parseFloat('3'); // => 3
Number('3'); // => 3
parseFloat('1.501'); // => 1.501
Number('1.501'); // => 1.501
parseFloat('1e10'); // => 10000000000
Number('1e10'); // => 10000000000

So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):

parseFloat('1x'); // => 1
Number('1x'); // => NaN

In addition, Number understands hexadecimal input while parseFloat does not:

parseFloat('0x10'); // => 0
Number('0x10'); // => 16

But Number acts weird with empty strings or strings containing only white space:

parseFloat(''); // => NaN
Number(''); // => 0
parseFloat(' \r\n\t'); // => NaN
Number(' \r\n\t'); // => 0

On the whole, I find Number to be more reasonable, so I almost always use Number personally (and you'll find that a lot of the internal JavaScript functions use Number as well). If someone types '1x' I prefer to show an error rather than treat it as if they had typed '1'. The only time I really make an exception is when I am converting a style to a number, in which case parseFloat is helpful because styles come in a form like '3px', in which case I want to drop the 'px' part and just get the 3, so I find parseFloat helpful here. But really which one you choose is up to you and which forms of input you want to accept.

Note that using the unary + operator is exactly the same as using Number as a function:

Number('0x10'); // => 16
+'0x10'; // => 16
Number('10x'); // => NaN
+'10x'; // => NaN
Number('40'); // => 40
+'40'; // => 40

So I usually just use + for short. As long as you know what it does, I find it easy to read.

What is the difference between Number(...) and parseFloat(...)

No. Both will result in the internal ToNumber(string) function being called.

From ES5 section 15.7.1 (The Number Constructor Called as a Function):

When Number is called as a function rather than as a constructor, it performs a type conversion...

Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else returns +0.

From ES5 section 15.1.2.3 (parseFloat (string)):

...
If neither trimmedString nor any prefix of trimmedString satisfies the syntax of a StrDecimalLiteral (see 9.3.1)
...

And 9.3.1 is the section titled "ToNumber Applied to the String Type", which is what the first quote is referring to when it says ToNumber(value).


Update (see comments)

By calling the Number constructor with the new operator, you will get an instance of the Number object, rather than a numeric literal. For example:

typeof new Number(10); //object
typeof Number(10); //number

This is defined in section 15.7.2 (The Number Constructor):

When Number is called as part of a new expression it is a constructor: it initialises the newly created object.

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

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



Related Topics



Leave a reply



Submit