@zdepot/utils
v1.2.2
Published
Safety Type Conversion Utility Library, providing type judgment and conversion methods with fallback values
Maintainers
Readme
@zdepot/utils
Safe type conversion tool library, which provides the method of type judgment and conversion with bottom value, to ensure that your code will not throw exceptions because of type problems.
Features
✅ Type Safety - Accurate type detection based on Object.prototype.toString
✅ Fallback Protection - All conversion methods have default fallback values to prevent runtime errors
✅ JSON Parsing - Smart JSON parsing with automatic type detection
✅ Circular References - Safe JSON serialization with automatic circular reference and function handling
✅ TypeScript Support - Complete TypeScript type definitions
✅ Tree-shaking - Side-effect free, compatible with bundler optimization
Installation
npm install @zdepot/utilsUsage
// 默认导入
import safe from '@zdepot/utils'
// 或命名导入
import { safe } from '@zdepot/utils'API
isSameType(a, b)
Checks if two values are of the same type, using Object.prototype.toString for precise detection.
safe.isSameType([], []) // true
safe.isSameType({}, []) // false
safe.isSameType(1, '1') // falsearray(value)
Ensures an array is returned. Returns the input directly if it's an array; parses JSON array strings automatically; otherwise returns an empty array [].
safe.array([1, 2]) // [1, 2] → number[](按元素类型推导)
safe.array('[1,2]') // [1, 2]
safe.array('{"a":1}') // [] (对象是数组类型不匹配)
safe.array('hello') // []
safe.array(null) // []
// 输入是 unknown 时,可显式指定元素类型
safe.array<string>(input) // string[]string(value, fallback?)
Ensures a string is returned. Returns the input directly if it's a string, otherwise returns the fallback value (default "").
safe.string('hello') // 'hello'
safe.string(123) // ''
safe.string(123, 'default') // 'default'number(value, fallback?)
Ensures a number is returned. Uses Number() for conversion, returns fallback value (default 0) if result is NaN or Infinity.
safe.number(123) // 123
safe.number('456') // 456
safe.number('abc') // 0
safe.number('abc', -1) // -1
safe.number(Infinity) // 0jsonParse(value, fallback)
JSON.parse with fallback value. Returns fallback if parsing fails or result type doesn't match fallback type.
safe.jsonParse('{"a":1}', {}) // { a: 1 }
safe.jsonParse('invalid', {}) // {}
safe.jsonParse('"hello"', []) // [] (type mismatch)
safe.jsonParse(null, {}) // {}jsonParseObj(value, fallback)
Enhanced jsonParse that only processes strings starting with [ or { (objects/arrays), otherwise returns fallback directly. Built-in length limit prevents DoS attacks.
safe.jsonParseObj('{"a":1}', {}) // { a: 1 }
safe.jsonParseObj('[1,2]', []) // [1, 2]
safe.jsonParseObj('"hello"', {}) // {} (doesn't start with [ or {)
safe.jsonParseObj('invalid', {}) // {}split(value, splitStr)
Safe String.split. Empty strings return [] instead of [''], errors also return [].
safe.split('a,b,c', ',') // ['a', 'b', 'c']
safe.split('', ',') // []
safe.split(null, ',') // []boolean(value, fallback?)
Ensures a boolean is returned. Strings and numbers share the same semantics: 1/'1' are truthy, 0/'0' are falsy. true/false strings are case-insensitive and trimmed.
safe.boolean(true) // true
safe.boolean('TRUE') // true
safe.boolean(1) // true
safe.boolean('1') // true
safe.boolean('false') // false
safe.boolean(0) // false
safe.boolean('0') // false
safe.boolean('hello') // false (fallback value)date(value, fallback?)
Ensures a valid Date object is returned. Supports Date objects, timestamps, and date strings.
- Numeric strings are parsed as timestamps (
'1700000000000'equals1700000000000) - An invalid input Date (or an invalid fallback) falls through to the next fallback level
safe.date(new Date()) // returns as-is
safe.date(1700000000000) // new Date(1700000000000)
safe.date('1700000000000') // new Date(1700000000000)(数字字符串按时间戳解析)
safe.date('2023-01-01') // new Date('2023-01-01')
safe.date('invalid') // new Date() (current time)
safe.date('invalid', fallback) // fallback
safe.date(new Date('x'), fb) // fb (Invalid Date 走兜底)function(value, fallback?)
Ensures a function is returned. Returns the input directly if it's a function, otherwise returns the fallback value (default empty function).
safe.function(fn) // fn
safe.function(null) // () => undefined
safe.function(null, () => 'hi') // () => 'hi'nonEmptyString(value, fallback?)
Ensures a non-empty string is returned. Returns the input if it's a non-empty string, otherwise returns the fallback value.
safe.nonEmptyString('hello') // 'hello'
safe.nonEmptyString(' ') // '' (whitespace only)
safe.nonEmptyString('') // ''
safe.nonEmptyString(123, 'N/A') // 'N/A'email(value, fallback?)
Ensures a valid email string is returned.
safe.email('[email protected]') // '[email protected]'
safe.email('invalid') // ''
safe.email('bad', '[email protected]') // '[email protected]'timestamp(value, fallback?)
Ensures a valid timestamp is returned.
safe.timestamp(1700000000000) // 1700000000000
safe.timestamp(new Date()) // date.getTime()
safe.timestamp('2023-01-01') // 1672531200000
safe.timestamp('invalid', 0) // 0jsonStringify(value, indent?)
Safe JSON serialization. Automatically handles circular references and functions without throwing.
Only references that already appear on the ancestor chain are treated as circular—the same object repeated across different branches is serialized normally.
safe.jsonStringify({ a: 1 }) // '{"a":1}'
safe.jsonStringify({ fn: () => {} }) // '{"fn":"[Function]"}'
const obj: any = { name: 'test' }
obj.self = obj
safe.jsonStringify(obj) // '{"name":"test","self":"[Circular]"}'
// 重复引用不是循环引用,会被正常展开
const shared = { x: 1 }
safe.jsonStringify([shared, shared]) // '[{"x":1},{"x":1}]'Use Cases
// API response handling
const data = safe.jsonParse(response.data, defaultValue)
const items = safe.array(data.items)
// Config file parsing
const config = safe.jsonParseObj(fs.readFileSync('config.json', 'utf-8'), {})
// User input processing
const username = safe.string(input.username, 'guest')
const age = safe.number(input.age, 0)
// String splitting
const parts = safe.split(input.tags, ',') // avoids split(',a', ',') returning ['', 'a']License
MIT
