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
| Parameter | Type | Description |
|---|---|---|
value | string | A 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:
- 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). - Booleans —
'true','yes','y'(case-insensitive) →true;'false','no','n'→false. - Integers — strings matching
/^-?\d+$/are parsed withparseInt(..., 10)if the result is a safe integer. - Floats — strings matching
/^-?\d+\.\d+$/are parsed withparseFloat. - 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') — passcoerce: falsetoobjectify()instead, or handle the type downstream. - You need locale-aware number parsing —
parseFloat/parseIntare locale-independent but only handle decimal notation; scientific notation ('1e5') is NOT coerced to a number.
Pitfalls
- NEVER use
coerceValueon 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 float3.14. - NEVER pass leading-zero strings you want preserved as strings (e.g., zip codes
'01234') — BECAUSE the integer regex matches andparseInt('01234', 10)returns1234. - NEVER rely on
'on'/'off'being coerced to booleans — BECAUSE onlytrue/false/yes/no/y/nare 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)