Skip to content

objectenvy / coerceValue

Function: coerceValue()

ts
function coerceValue(value): string | number | boolean | (string | number | boolean)[];

Defined in: utils.ts:157

Coerce a raw environment variable string to its most appropriate JavaScript type.

Parameters

ParameterTypeDescription
valuestringA raw string value from an environment variable.

Returns

string | number | boolean | (string | number | boolean)[]

The coerced value: boolean, number, a string, or an array thereof.

Remarks

Applies the following rules in order:

  1. Arrays — if the string contains a comma (,), it is split on commas, each element is trimmed and filtered for empty strings, and each element is coerced recursively. If only one non-empty element remains after splitting, the single value is returned (not wrapped in an array).
  2. Booleans'true', 'yes', 'y' (case-insensitive) → true; 'false', 'no', 'n'false.
  3. Integers — strings matching /^-?\d+$/ are parsed with parseInt(..., 10) if the result is a safe integer.
  4. Floats — strings matching /^-?\d+\.\d+$/ are parsed with parseFloat.
  5. Strings — everything else is returned unchanged.

Use When

  • You want to apply the same type-coercion rules that objectify() uses internally to an individual value.
  • You're processing env values outside objectify() and need consistent boolean/number parsing.

Avoid When

  • The value must stay a string regardless of content (e.g., '123' must stay '123') — pass coerce: false to objectify() instead, or handle the type downstream.
  • You need locale-aware number parsing — parseFloat/parseInt are locale-independent but only handle decimal notation; scientific notation ('1e5') is NOT coerced to a number.

Pitfalls

  • NEVER use coerceValue on values that use commas as decimal separators (e.g., '3,14' in some locales) — BECAUSE the function will treat this as an array [3, 14] rather than the float 3.14.
  • NEVER pass leading-zero strings you want preserved as strings (e.g., zip codes '01234') — BECAUSE the integer regex matches and parseInt('01234', 10) returns 1234.
  • NEVER rely on 'on'/'off' being coerced to booleans — BECAUSE only true/false/yes/no/y/n are in the boolean equivalents set; 'on' stays as the string 'on'.

Example

ts
import { coerceValue } from 'objectenvy';
coerceValue('3000');        // 3000 (number)
coerceValue('true');        // true (boolean)
coerceValue('yes');         // true (boolean)
coerceValue('3.14');        // 3.14 (number)
coerceValue('localhost');   // 'localhost' (string unchanged)
coerceValue('a,b,c');       // ['a', 'b', 'c'] (array)
coerceValue('1,2,3');       // [1, 2, 3] (array of numbers)

See

objectify which calls coerceValue internally when coerce: true (the default)

Released under the MIT License.