Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-coerce-nan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bomb.sh/args": patch
---

Fix coerce() returning NaN for non-numeric digit-starting strings
6 changes: 4 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,10 @@ const coerce = (value?: string, type?: "string" | "boolean" | "array") => {
if (!value) return value;
if (value.length > 3 && BOOL_RE.test(value)) return value === "true";
if (value.length > 2 && QUOTED_RE.test(value)) return value.slice(1, -1);
if ((value[0] === "." && /\d/.test(value[1])) || /\d/.test(value[0]))
return Number(value);
if ((value[0] === "." && /\d/.test(value[1])) || /\d/.test(value[0])) {
const n = Number(value);
if (!isNaN(n)) return n;
}
return value;
};

Expand Down
20 changes: 20 additions & 0 deletions test/flags.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,26 @@ describe("special cases", () => {
});
});

describe("coerce NaN guard", () => {
it("version-like string as positional is kept as string", () => {
expect(parse(["3.7.1"])).toEqual({ _: ["3.7.1"] });
});

it("digit-prefixed non-numeric string as positional is kept as string", () => {
expect(parse(["1abc"])).toEqual({ _: ["1abc"] });
});

it("version-like string as flag value is kept as string", () => {
expect(parse(["--version", "3.7.1"])).toEqual({ _: [], version: "3.7.1" });
});

it("valid numbers still coerce correctly", () => {
expect(parse(["42"])).toEqual({ _: [42] });
expect(parse([".5"])).toEqual({ _: [0.5] });
expect(parse(["3.14"])).toEqual({ _: [3.14] });
});
});

describe("boolean flags", () => {
it("should handle long-form boolean flags correctly", () => {
const input = ["--add"];
Expand Down