In TypeScript, how does "number" differ from "Number"?

Within the realm of TypeScript, there exist two distinct variations of the "number" type. The first is denoted as lowercase number, whereas the second is represented in uppercase as Number. Attempting to display number results in a compiler error:

console.log(number); //-> error TS2693: 'number' only refers to a type

In contrast, viewing Number provides the standard function description:

console.log(Number); //-> [Function: Number]

This behavior is anticipated since Number serves as a pre-existing JavaScript constructor documented here. Nevertheless, the nature of number remains ambiguous.

From the error message, it appears that number does not embody a distinct value like

Number</code. Despite this, it is utilized in variable and function declarations as if it were a value:</p>
<pre class="lang-js"><code>var two: number = 2;
function sqr(x: number) { return x; }

In contrast, user-defined types such as classes appear as separate values (and exhibit the standard function description when printed). Adding complexity, Number can be employed in annotations similarly to number:

var two: Number = 2;

Similar scenarios arise with string and String, any and Object, and so forth.

Therefore, the inquiry stands: What exactly are number, string, etc in TypeScript, and how do they differ from the built-in constructors?

Answer №1

number is exclusive to TypeScript - it represents a primitive type that refers to a numerical value.

However, based on the error message, it appears that number is not a distinct value like Number.

Indeed - it's a type that does not exist in compiled code.

a distinct value like Number. Conversely, user-defined types such as classes seem to be distinct values (as they display the standard function description).

Yes. Classes, including Number, are unique. They serve a dual purpose, which may seem counterintuitive:

  • They establish a JavaScript class (usable in compiled code)
  • They also define an interface for the class (specific to TypeScript)

If you utilize Number in a context where a type is required, TypeScript won't raise an issue because Number functions as an interface.

If you use Number in a context where a value (something present in compiled code) is expected, TypeScript won't raise an issue because Number also serves as a global constructor.

In essence, the two instances of Number below refer to entirely separate entities:

// pointing to TypeScript Number interface
let foo: Number;

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

Using Number in TypeScript is peculiar, as it technically refers to a number generated using new:

const theNum = new Number(6);

There is hardly a justification for doing so. It's preferable to use a plain primitive number without an object wrapper instead.

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

Answer №2

According to https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean:

When it comes to JavaScript, there are three fundamental primitives in common usage: string, number, and boolean. Each of these corresponds to a specific type in TypeScript. As expected, these type names align with what you’d see with the JavaScript typeof operator for values of those types:

  • string is used for string values such as "Hello, world"
  • number is dedicated to numbers like 42. JavaScript doesn't differentiate between integers and floats, so everything falls under number
  • boolean encompasses the values true and false

The type names String, Number, and Boolean (with initial capital letters) are technically valid, but they refer to specific built-in types that are rarely used in regular code. Stick to string, number, or boolean for your types.

(Don't forget about types for null and undefined too)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to obtain cookies on a Server-side component in the latest version of Next.js?

import axios from "axios"; const Api = axios.create({ baseURL: "http://127.0.0.1:5000", }); axios.defaults.headers.common["Authorization"] = cookie; In server-side environment, document.cookie is not accessible. Alternat ...

What is the best way to define a union type that encompasses all values within a field of an array?

I have a function that takes an array and a field parameter, but I want to restrict the field's type to a union type that describes all the values of the fields in the array. Here's an example: interface item { name: string, value: number ...

"Unlocking the secret to fetching the id of the clicked element within a Highchart context menu

Is it possible to retrieve the id of a clicked button on the highchart context menu? Alternatively, is there a way to execute the click function twice? const contextButtonArray = []; contextButtonArray.push({ { text: 'TEST BUTTON&ap ...

Clear Dropdown Selections prior to Submitting

When trying to change the value of the first dropdown list and reset the second dropdown before submission, I encountered an issue where the second dropdown still retains its previous selection upon submission. There is no submit button as the form is subm ...

Error Encountered: Angular JS Throwing Unhandled Injection Error

I am having trouble validating the fields in my index.html and js files. I keep seeing errors, even after trying different versions of angular-route.min.js and angular.js. AngularJs | Basic Login Form <body ng-app="myApp"> ...

Platform designed to simplify integration of high-definition imagery and scalable vector illustrations on websites

In the ever-evolving world of technology, some clients support advanced features like svg while others do not. With the rise of high resolution devices such as iPhone 4+ and iPad 3rd gen., it has become crucial to deliver graphics that can meet these stand ...

When a client sends a GET request to the server, an error occurs due to the absence of 'Access-Control-Allow-Origin' header in

I am encountering an issue with my node/express js application running on localhost while making a 'GET' request to Instagram's api. The error message I keep receiving is: XMLHttpRequest cannot load https://api.instagram.com/oauth/authorize ...

The function's name has been obscured by the name of its parameter

Caution: ECMAScript 5 (ES5) strictly prohibits the use of arguments.callee(). To avoid this, either name function expressions or opt for a function declaration that calls itself. [MDN] How can we refer to the o function within itself in this scenario? fun ...

the object '[object Object]' of a distinct supporting nature

I encountered an error stating "ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays." This is my TypeScript file: this.list = data.json(); ...

jQuery and HTML: Need help enabling an <input> or <select> element?

Currently, I am using Mozilla Firefox 14.0.1 and Google Chrome 20.0.1132.57 (which I believe is the latest version). The code I am working with looks like this: http://jsfiddle.net/SVtDj/ Here is what I am trying to accomplish: Type something into inpu ...

In a production environment, an ENOENT error in Next.js was triggered by fs.readdirSync

Utilizing the Next.js App Router, I attempted to retrieve all my markdown posts stored in files by scanning a directory using fs.readdirSync(). While everything worked flawlessly locally, upon deploying on Vercel, an unexpected issue arose. The code was e ...

Leveraging the power of the wildcard feature to execute a variety of scripts when running

Inside my package.json file, I currently have the following scripts block: "scripts": { "test": "node tests/*-test.js" } In the tests folder, I have files named a-test.js and b-test.js. This can be confirmed by using the command ls tests/*-test.js. ...

Error encountered while compiling ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js

I've encountered a frustrating error message: Failed to compile ./node_modules/@material-ui/core/ButtonBase/ButtonBase.js Module not found: Can't resolve '@babel/runtime/helpers/builtin/assertThisInitialized' in 'E:\IT&bsol ...

Triggering jQuery accordion when clicked

I have a challenge to tackle - I want to create an accordion system that can display and hide quotes at various points on the page. My desired outcome is to have one quote displayed per accordion panel. When I expand an accordion, I want to show the cont ...

Show a virtual numeric keypad on the HTML input fields when they are set as type text specifically for mobile devices in a unique situation

When accessing the following web page from a mobile device, I currently have number input fields with comma separators added. However, in order to implement the comma separation function, I had to set the input type to text. This resulted in showing an alp ...

jQuery Toggle and Change Image Src Attribute Issue

After researching and modifying a show/hide jQuery code I discovered, everything is functioning correctly except for the HTML img attribute not being replaced when clicked on. The jQuery code I am using: <script> $(document).ready(function() { ...

Tips for accelerating the loading of data retrieved through ajax requests

At present, data is being fetched in array form from a PHP script. I have noticed that when retrieving 40 sets of data, it takes approximately 20 seconds for the data to load. This delay may be due to ajax having to wait until all the results are gathered. ...

Ways to retrieve every span within a string variable that possesses a specific class designation

I'm having trouble listing out all spans with the class "ansspans." There may be one or more span elements with the "ansspans" class, and I need to retrieve them along with their content in order to iterate through them. Can someone explain how to do ...

What is the reason that TypeScript cannot replace a method of the base class with a subtype?

Here's a straightforward example. type Callback<T> = (sender: T) => void; class Warehouse<T> { private callbacks: Callback<T>[]; public constructor(callbacks: Callback<T>[]) { this.callbacks = callbacks; ...

What is the best way to utilize multiple models under a single root in ReactJS?

Greetings! I currently have a root structure in the following code snippet: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <button >Platform</button> <button >Game</button> < ...