Skip to content

fix: don't throw when a coerce function returns a non-primitive - #569

Closed
naveentehrpariya wants to merge 1 commit into
yargs:mainfrom
naveentehrpariya:fix-looks-like-number-non-primitive
Closed

naveentehrpariya wants to merge 1 commit into
yargs:mainfrom
naveentehrpariya:fix-looks-like-number-non-primitive

Conversation

@naveentehrpariya

Copy link
Copy Markdown

Fixes #352.

The bug

looksLikeNumber converts its argument to a string to run its regex checks:

if (/^0x[0-9a-f]+$/i.test(x)) return true

A coerce function is user-supplied and can return any value, and maybeCoerceNumber passes that return value straight into looksLikeNumber. For an object with no reachable toString — such as the null prototype object returned by pg-connection-string's parse — that conversion throws:

TypeError: Cannot convert object to primitive value

which yargs then surfaces as an opaque YError, with the original stack lost.

parser(['--db', 'postgresql://db/things'], {
  coerce: {
    db: () => {
      const connection = Object.create(null)
      connection.host = 'db'
      return connection
    }
  }
})
// TypeError: Cannot convert object to primitive value

The fix

Return false for anything that is neither a number nor a string. Such a value can never be parsed as a number, so there is nothing to lose by skipping the string checks — this is the direction both @bcoe and @groner suggested on the issue.

Tests

  • looksLikeNumber returns false instead of throwing for a null prototype object and for an object whose toString throws.
  • The parser applies a coerce function that returns a prototype-less object and keeps the returned value intact.

Both fail on main with TypeError: Cannot convert object to primitive value. With the fix, npm test is 364 passing / 0 failing, npm run test:typescript 20 passing, and npm run check is clean.

`looksLikeNumber` converts its argument to a string to run its regex
checks. A coerce function can return any value, and converting one to a
string throws for objects with no `toString` -- for example the null
prototype object returned by `pg-connection-string`'s `parse`:

    TypeError: Cannot convert object to primitive value

Return `false` for anything that is neither a number nor a string: such a
value can never be parsed as a number anyway.

Fixes yargs#352
@naveentehrpariya
naveentehrpariya force-pushed the fix-looks-like-number-non-primitive branch from d038a5d to 74a5ef2 Compare November 8, 2026 10:43
@shadowspawn

Copy link
Copy Markdown
Member

Unsolicited Pull Requests may be closed without discussion.

For more see Contributing and AI Policy.

@shadowspawn shadowspawn closed this Nov 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

maybeCoerceNumber bombs if coerce produced an object without toString

2 participants