TypeScript Reference ยท Primitive and Special Types
The TypeScript number type
Reference for the number type in TypeScript: 64-bit floats, NaN and Infinity, safe integers, parsing, rounding, numeric separators and bigint.
number is the single numeric type for integers and decimals alike. At runtime every number is a 64-bit IEEE 754 double, so there is no separate int or float. Hex, octal and binary literals (0xff, 0o17, 0b101) and numeric separators (1_000_000) are all just number.
Three special values live in the type: NaN (not a number), Infinity and -Infinity. TypeScript cannot tell them apart from ordinary numbers, so you must guard against them yourself.
let price: number = 19.99; const million = 1_000_000; const mask: number = 0b1010;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
let n: number; const big: number = Number.MAX_VALUE; type Percent = number; // alias only; the compiler does not enforce a range
| Member | Description |
|---|---|
Number.MAX_SAFE_INTEGER |
9007199254740991, the largest integer that is represented exactly. |
Number.EPSILON |
Gap between 1 and the next double; useful for tolerant comparison. |
Number.isInteger, isFinite, isNaN, isSafeInteger |
Type-strict checks that do not coerce their argument. |
Number(x) |
Converts with coercion: "" becomes 0, "12px" becomes NaN. |
Usage notes
- No integer type. Bitwise operators work on 32-bit signed integers, so
2 ** 32 | 0is0. Usebigintfor exact large integers. - Money. Do not store currency as floats; keep integer cents or use a decimal library.
- NaN is not equal to itself. Use
Number.isNaN(x). The globalisNaNcoerces first and saystruefor"abc". toFixedreturns a string. It rounds by the binary value (1.005.toFixed(2)is"1.00").- Branded numbers. To keep
MetersandSecondsapart, use a brand:type Meters = number & { readonly __unit: "m" }. - Narrowing.
typeof x === "number"narrows, and includesNaN. - Enums. Numeric enum members are assignable to and from
number, which weakens checking; prefer string literal unions. - Numeric separators exist only in source code;
Number("1_000")isNaN.
Related
- bigint, Number literal types, string, boolean
- Lessons: Primitive types, Type inference