parseNumber
Parses a value into a finite number. This parser combines the normalizeNumber normalizer with the validateNumber primitive validator to produce a canonical finite numeric value.
The parser never throws and never mutates input. It returns a structured ParseResult<number> describing success or failure.
Signature
function parseNumber(
value: unknown,
field?: string
): ParseResult<number>
Behavior
- Accepted inputs:
- Primitive finite numbers (e.g., 42, 0, -3.14)
- Numeric strings (e.g., "42", " 3.14 ")
- Strings are trimmed before parsing
- Only finite results are accepted
- Rejected inputs:
NaNInfinity-Infinity- These produce the error: "Value could not be normalized into a finite number"
- Non-numeric strings ("abc")
- Empty or whitespace-only strings
- Arrays and objects.
- Functions
- Booleans
nullandundefined.- Boxed
Numberobjects (new Number(5)).- These produce the error: "Value must be a number".
Normalization rules
- Finite numbers are returned unchanged.
- Numeric strings are trimmed and parsed.
- All other values return null from the normalizer.
Returns
A ParseResult<number> object:
ok: true: And the finite number when parsing succeeds.ok: false, value: nullAnd a list of issues when parsing fails.
Examples
parseNumber(" 42 ")
// { ok: true, value: 42, issues: [] }
parseNumber(NaN)
// { ok: false, value: null, issues: ["Value could not be normalized into a finite number"] }
parseNumber("abc")
// { ok: false, value: null, issues: ["Value must be a number"] }
parseNumber(Infinity)
// { ok: false, value: null, issues: ["Value could not be normalized into a finite number"] }
Notes
- This parser is intentionally permissive with numeric strings.
- For integer-only parsing, use parseInteger.
- For strict primitive-number-only behavior (no string parsing), use validateNumber directly.