The string to parse.
Result.ok(parsedInt) for valid input, otherwise Result.err
wrapping an Error describing the invalid input.
assert.strictEqual(
Result.unwrapOkOr(Num.safeParseInt('123'), Number.NaN),
123,
);
assert.strictEqual(
Result.unwrapOkOr(Num.safeParseInt('12.9'), Number.NaN),
12,
);
assert.strictEqual(
Result.unwrapOkOr(Num.safeParseInt('-12.9'), Number.NaN),
-12,
);
assert.strictEqual(Number.parseInt('-12.9', 10), -12);
// Native `parseInt` ignores trailing non-numeric characters
assert.strictEqual(Number.parseInt('123abc', 10), 123);
assert.isTrue(Number.isNaN(Number('123abc')));
assert.isTrue(Result.isErr(Num.safeParseInt('123abc')));
// Whitespace is not a valid integer, so we return an error instead of coercing to 0.
assert.isTrue(Number.isNaN(Number.parseInt(' ', 10)));
assert.strictEqual(Number(' '), 0); // Native `Number` coerces whitespace to 0
assert.isTrue(Result.isErr(Num.safeParseInt('')));
assert.strictEqual(Result.unwrapOk(Num.safeParseInt(' ')), undefined);
Safely parses a base-10 integer from a string, returning a Result that is
Ok<Int>for valid input andErr<Error>otherwise.This is a stricter alternative to both
parseIntandNumber:parseInt('12abc', 10)(which returns12), trailing non-numeric characters make the whole input invalid and yieldErr.Number('')/Number(' ')(which return0), empty or whitespace-only input yieldsErr.The empty-string case is rejected by delegating to
parseInt(which returnsNaNthere) rather than hard-coding a check, while the trailing- garbage case is rejected viaNumber. Valid input is truncated toward zero, so'12.9'becomes12and'-3.5'becomes-3.Only base 10 is supported. Use
Result.unwrapOk(optionally with a?? Number.NaNfallback) orResult.unwrapOkOrto get a plain number back.