typepurify
v0.5.15
Published
The ultimate zero-schema JSON cleaner for TypeScript. Recursively remove null, undefined, and empty objects while preserving exact type inference. No Zod or Yup needed.
Maintainers
Readme
New in v1.6.14: Added WasmModule — WebAssembly binding loader with fallback mode for high-performance transformations.
🚀 Overview
typepurify is the core engine of the TypePurify Ecosystem. It is a lightning-fast, zero-schema data cleaner designed to deeply strip null, undefined, and optionally empty strings, arrays, or objects from your data maps while keeping your TypeScript types perfectly aligned.
Instead of writing complex Zod or Joi schemas just to clean a payload, typepurify automatically re-infers your types at compile-time and safely handles nested structures natively.
🌟 Ecosystem Expansion: We are actively expanding! Check out our new packages like
@typepurify/fetchfor a safe, auto-purifying wrapper around the nativefetchAPI!
📦 Installation
Clean, copy-pasteable installation for your favorite package manager:
npm install typepurifyyarn add typepurifypnpm add typepurify🛠 Supported Data Types
typepurify intelligently traverses your data while respecting language primitives.
✅ Deeply Purified:
Object(Nested keys are recursively checked)Array(Nullish elements are removed, holes are collapsed)Map(Keys & values are deep-cleaned)Set(Nullish values are dropped)
🛡️ Safely Ignored (Preserved as-is):
Date,RegExp,ErrorPromiseArrayBuffer,SharedArrayBuffer,TypedArray(e.g.,Uint8Array)WeakMap,WeakSet,Function
💻 Usage & Visual Examples
1. Standard Cleaning (Input vs Output)
Instantly clean up null and undefined properties from a messy API response.
import { clean } from 'typepurify';
// ❌ Dirty Input Data
const messyPayload = {
id: 101,
profile: {
title: null,
geo: 'IN',
},
tags: ['React', null, 'TypeScript'],
};
// 🧹 Run TypePurify
const pristinePayload = clean(messyPayload);
// ✨ Purified Output
/*
{
id: 101,
profile: {
geo: 'IN'
},
tags: ['React', 'TypeScript']
}
*/(💡 Notice: TypeScript automatically updates the type of pristinePayload to remove null from profile.title and tags!)
2. Aggressive Cleaning (Stripping Empty Values)
Need to remove empty strings, arrays, and objects? Use the options configuration.
import { clean } from 'typepurify';
// ❌ Dirty Input Data
const messyPayload = {
id: 102,
description: '',
metadata: {},
hobbies: [],
valid: true,
};
// 🧹 Run TypePurify with Options
const ultraCleanPayload = clean(messyPayload, {
stripEmptyStrings: true,
stripEmptyArrays: true,
stripEmptyObjects: true,
});
// ✨ Purified Output
/*
{
id: 102,
valid: true
}
*/3. High-Performance JSON Parsing (cleanParse) (v1.4.0 🚀)
For maximum performance when fetching data from an API, skip JSON.parse() entirely and use cleanParse. This parses the raw JSON string and deep-cleans it in a single pass, completely eliminating the memory overhead of intermediate objects.
import { cleanParse } from 'typepurify';
// ❌ Raw Dirty JSON String from API
const rawJson = '{"id": 103, "name": " Jane Doe ", "emptyList": [], "nullProp": null}';
// 🧹 Parse and Clean in one pass (Up to 25% faster)
const pristinePayload = cleanParse(rawJson, {
stripEmptyArrays: true,
trimStrings: true,
});
// ✨ Purified Output
/*
{
id: 103,
name: "Jane Doe"
}
*/⚡ API Reference
clean<T>(obj: T, options?: CleanOptions): DeepRequired<T>
Recursively deep-cleans null/undefined values from objects and arrays, dynamically re-inferring compile-time types without generating heavy schemas.
deepOmit<T, K>(obj: T, keys: K[] | Set<K>) & deepPick<T, K>(obj: T, keys: K[] | Set<K>)
Highly optimized $O(1)$ constant-time utilities that deep-traverse your payload to instantly remove (deepOmit) or selectively extract (deepPick) specific keys at any nesting level. Using a Set makes this vastly more performant than lodash on large payloads!
cleanInPlace<T>(obj: T, options?: CleanOptions): DeepRequired<T>
Operates exactly like clean(), but mutates the original payload directly instead of allocating new objects in memory. Offers maximum performance and zero memory overhead for massive payloads.
cleanAsync<T> & cleanInPlaceAsync<T>
Asynchronous versions of the above that yield to the event loop every 1,000 iterations to prevent blocking the main thread when processing gigantic API payloads.
cleanParse<T>(json: string, options?: CleanOptions): DeepRequired<T> (v1.4.0 🚀)
A specialized JSON parser that deeply cleans a raw JSON string in a single pass. By skipping standard JSON.parse and its intermediate object allocation, cleanParse is incredibly memory-efficient and up to 25% faster for massive JSON payloads.
MemoryBuffer<T>(capacity?: number) (v1.6.3 🚀)
An optimized in-memory chunk buffer for streaming data purification operations with customizable capacity boundaries and .flush(), .push(), .size() methods.
Options Configuration (CleanOptions)
stripAllEmpty: Aggressively strips all empty arrays, strings, objects, sets, and maps in a single pass (v1.6.11 🚀)stripEmptyStrings: Removes""stripEmptyArrays: Removes[]stripEmptyObjects: Removes{}trimStrings: Trims whitespace from strings before processingstripWhen: Custom predicate function (e.g.(val) => val === 'N/A')transform: Custom callback to mutate values before they are processed
⚡ Why typepurify? (vs. Zod / Lodash)
| Feature | typepurify | Zod / Joi | Lodash |
| :----------------------- | :--------------------------- | :----------------------- | :--------------------- |
| Package Size | < 1 kB ⚡ | ~550 kB 🐢 | ~1.4 MB 🐌 |
| TypeScript Inference | Perfect (Automatic) | Requires Manual Schemas | Destroys Types (any) |
| Boilerplate Code | Zero (1 Line) | High (Hundreds of lines) | Medium |
| Execution Speed | Extreme (cleanInPlace) | Slow (Schema parsing) | Fast |
🆕 New in v1.6.8
inferSchemaBatch(objects) — Batch Schema Inferencer
Runs inferSchema across an array of objects in a single call, returning an array of schema maps.
import { inferSchemaBatch } from 'typepurify';
const schemas = inferSchemaBatch([
{ id: 1, name: 'Alice' },
{ id: 2, active: true, tags: ['ts'] },
]);
// => [{ id: 'number', name: 'string' }, { id: 'number', active: 'boolean', tags: 'array' }]createWasmBindingsAdapter(wasmModule) — WASM Bindings Adapter
Wraps a WebAssembly module exports object as a typed JavaScript facade.
import { createWasmBindingsAdapter } from 'typepurify';
const wasmModule = await WebAssembly.instantiate(buffer);
const adapter = createWasmBindingsAdapter(wasmModule.exports);
const result = adapter.call('add', 1, 2);Contributing
Contributions, issues, and feature requests are welcome! See our Contributing Guidelines for more details.
👨💻 About the Author
Vallarasu Kanthasamy
Full-Stack & Systems Engineer
I build lightweight, high-performance developer utilities and media automation engines. My engineering focus centers on zero-dependency architecture, defensive data structures, and advanced TypeScript type systems that normalize boundaries in enterprise applications.
🌐 Digital Ecosystem & Platforms
Developer Tools & Extensions
- Auto Console Log (VS Code) – Lightning-fast debugging for JS/TS.
- Opacity Adjuster (Chrome Extension)
- Tech Stack Checker (Chrome Extension)
- Universal Spreadsheet Markdown Editor
- Media Bucket Sync for Amazon S3 (WordPress)
Open Source & Resources
- Awesome Developer Resources – A curated list of high-value tools for developers.
- My Developer Resources & Blog
Connect With Me
- Portfolio: vallarasuk.in
- GitHub: github.vallarasuk.in
- LinkedIn: linkedin.vallarasuk.in
- Community: Join my WhatsApp Developer Squad
🛡️ License
MIT © Vallarasu Kanthasamy
📋 Changelog
v1.6.4 — Latest
New Features:
traverseObjectGraph(obj, visitor)— Recursively walks every node of an object graph, safely detecting and skipping circular references and prototype-polluting keys (__proto__,constructor,prototype).
import { traverseObjectGraph } from 'typepurify';
const graph = { a: { b: { c: 42 } } };
const visited: string[] = [];
traverseObjectGraph(graph, (value, path) => {
if (path.length > 0) visited.push(path.join('.'));
});
// visited => ['a', 'a.b', 'a.b.c']Bug Fixes:
- Fixed
transformcallback TypeScript inference — parameters are now explicitly typed as(val: any, key: any)to preventTS7006implicit-any errors in strict mode projects. - Fixed
deepOmitreturn type access on omitted keys requiring an explicitas anycast to satisfy strict TypeScript.
v1.2.0
- Added
traverseObjectGraphfor safe, circular-reference-aware graph traversal.
v1.0.1
- Added
pruneExcessto strip excess properties beyond a defined schema shape. - Added
preventMemoryLeaksto proactively clear WeakRef/WeakMap collections.
v0.4.6
- Added
deepMerge(target, source)to deeply merge objects and deduplicate arrays, andisPlainObject(val)for reliable type checking.
1.6.8 Updates
Includes new features.
