liveBook · Manning

Number type

As explained in Essential TypeScript 5, Third Edition

The number type is the built-in JavaScript type for numeric values.

The number type represents numeric values in JavaScript. Integers and floating-point values use the same built-in type, so a variable can hold values such as 12 or 100 without a separate integer type. section 3.3.1

Use number values carefully when JavaScript combines them with other types:

  • Adding a number to a numeric string can concatenate the values instead of calculating a total. section 3.2
  • The loose comparison between 100 and "100" succeeds, even though one value is a number and the other is a string. section 3.2
  • JavaScript infers a value's type dynamically, so assigning 100 to a variable previously holding a string changes the reported type to number. section 3.3.1

A numeric value mixed with text

let hatPrice = 100; let bootsPrice = "100"; let totalPrice = hatPrice + bootsPrice; console.log(totalPrice); // 100100 console.log(typeof hatPrice); // number The comparison may report equal, but the addition concatenates the number and string. A function expecting numbers can similarly produce NaN for "Hello" or 1.2 for true. section 3.2 section 7.2

Listing 3.6 Adding statements in the index.ts file in the primer folder
let hatPrice = 100;
console.log(`Hat price: ${hatPrice}`);
let bootsPrice = "100";
console.log(`Boots price: ${bootsPrice}`);

if (hatPrice == bootsPrice) {
    console.log("Prices are the same");    
} else {
    console.log("Prices are different");    
}

let totalPrice = hatPrice + bootsPrice;
console.log(`Total Price: ${totalPrice}`);

Inspect the complete price example and its output to see how comparison and addition treat a number alongside a numeric string. section 3.2

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Defines the unified numeric type and demonstrates dynamic reassignment, but defers detailed type coercion mechanics.
Examples
Demonstrates prices, typeof output, reassignment, and tax calculations receiving number, string, and boolean arguments.
What it assumes
Assumes familiar JavaScript variables and expressions while teaching primitive types and runtime type inspection through examples.
What you can do after
Diagnose unexpected calculations by checking whether values are numbers or strings and observing JavaScript coercion results.
How it connects
Connects number with dynamic typing, typeof, strings, booleans, and type coercion.

Also explained in

Compare how 6 books explain number type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.