Skip to content

util: allow styleText text param to accept non-string scalars#64452

Open
SparshGarg999 wants to merge 1 commit into
nodejs:mainfrom
SparshGarg999:fix/util-styletext-scalar-coercion
Open

util: allow styleText text param to accept non-string scalars#64452
SparshGarg999 wants to merge 1 commit into
nodejs:mainfrom
SparshGarg999:fix/util-styletext-scalar-coercion

Conversation

@SparshGarg999

Copy link
Copy Markdown

Summary

Allow util.styleText() to accept number, boolean, and bigint values for the text parameter, automatically coercing them to a string internally using String(text).

Description

Currently, passing a non-string value (such as a number, boolean, or bigint) to util.styleText() immediately throws ERR_INVALID_ARG_TYPE. This requires callers to manually cast non-string values before formatting them:

util.styleText('red', String(count)); // Before
util.styleText('red', count);         // After

This commit updates util.styleText to check the type of text and automatically coerce scalar values (number, boolean, bigint) to strings. The coercion happens before the fast path checks to avoid adding extra branching overhead for the common string case.

Non-string values that cannot be meaningfully coerced without potential issues (e.g. null, undefined, Symbol, Function, Object) still throw ERR_INVALID_ARG_TYPE.

Verification

Existing tests in test/parallel/test-util-styletext.js have been updated to check for scalar coercion behavior, and to verify that incorrect non-string types still throw.

Fixes: #63841

@nodejs-github-bot nodejs-github-bot added needs-ci PRs that need a full CI run. util Issues and PRs related to the built-in util module. labels Jul 12, 2026
Allow util.styleText() to accept
umber, �oolean, and �igint`nvalues for the 	ext parameter, automatically coercing them to string
via String(text).

Previously, passing anything other than a string would throw
ERR_INVALID_ARG_TYPE. This forced callers to wrap every non-string
value manually:

  util.styleText('red', String(count)) // before
  util.styleText('red', count)        // after

The coercion is applied before the fast path so there is no extra
branching cost for the common string case. Values that cannot be
meaningfully stringified (null, undefined, Symbol, Function, Object)
still throw ERR_INVALID_ARG_TYPE as before.

Fixes: nodejs#63841

Signed-off-by: SparshGarg999 <sparshgarg999@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-ci PRs that need a full CI run. util Issues and PRs related to the built-in util module.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[util.styleText] Allow text param to be any scalar value (ex. number, bool etc additionaly to string) which will be casted internally to string

2 participants