tiny-coerce
v3.2.0
Published
Convert strings to JavaScript types (boolean, null, number, object, array)
Maintainers
Readme
Tiny Coerce
Tiny coercion library for Client or Server. Converts string values to their appropriate JavaScript types (boolean, null, undefined, number, object, array).
Great for DOM data attributes, localStorage, and other cases where you need to store strings that represent typed values.
Installation
npm install tiny-coerceES Modules
import { coerce } from "tiny-coerce";CommonJS
const { coerce } = require("tiny-coerce");Usage
import { coerce } from "tiny-coerce";
// Basic coercion
coerce("true"); // true
coerce("false"); // false
coerce("null"); // null
coerce("undefined"); // undefined
coerce("123"); // 123
coerce("3.14"); // 3.14
// JSON coercion
coerce('{"a":1}'); // {a: 1}
coerce("[1,2,3]"); // [1, 2, 3]
coerce('"hello"'); // "hello"
// With options
coerce("true", {maxStringSize: 1000});API
coerce(arg, options = {})
Coerces a string value to its appropriate JavaScript type.
Parameters:
arg{*} - The value to coerceoptions{Object} (default:{}) - Coercion optionsmaxStringSize{number} (default:100000) - Maximum string size in bytes
Returns: {*} - The coerced value
Errors:
Throws an Error if:
- The string exceeds
maxStringSize
Coerced Types:
| Input | Output | Notes |
|-------|--------|-------|
| "true", "TRUE", "True" | true | Case-insensitive |
| "false", "FALSE", "False" | false | Case-insensitive |
| "null", "NULL", "Null" | null | Case-insensitive |
| "undefined" | undefined | Exact match |
| "123", "3.14" | 123, 3.14 | Any numeric string |
| '{"a":1}' | {a: 1} | Objects and arrays |
| '"hello"' | "hello" | JSON strings |
Testing
Tiny Coerce has 100% code coverage with its tests.
$ npm run coverage
ℹ start of coverage report
ℹ ----------------------------------------------------------
ℹ file | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ ----------------------------------------------------------
ℹ all files | 100.00 | 100.00 | 100.00 |
ℹ ----------------------------------------------------------
ℹ end of coverage reportSee coverage.txt for the latest coverage report.
Technical Details
See docs/TECHNICAL.md for in-depth technical documentation covering:
- Architecture and module structure
- Type coercion pipeline
- Security considerations
- Performance characteristics
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Run tests (
npm test) - Commit your changes (
git commit --no-verify -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
Copyright (c) 2026 Jason Mulligan
Licensed under the BSD-3-Clause license
