Typezy
A lightweight, zero-dependency TypeScript utility library for type checking, assertions, and validation.
Why Typezy?
Zero Dependencies
No external runtime dependencies to bloat your node_modules. Lean and fast.
Tree-shakeable
Import only what you need. Available in ESM and CJS builds for all environments.
Type-Safe
Acts as TypeScript type guards to perfectly narrow your types across your app.
React / Next.js Ready
Packed with utilities like safe URL parsing, Env validation, debounce, throttle, and a clsx-like `cx` function.
Installation
Install Typezy using your favorite package manager.
# npm
npm install typezy
# yarn
yarn add typezy
# pnpm
pnpm add typezy
Typezy provides submodules for better tree-shaking, though modern bundlers handle the root import fine.
import { isString } from 'typezy';
import { assertString } from 'typezy/assert';
import { validateEmail } from 'typezy/validate';
import type { DeepPartial } from 'typezy/types';
Type Checks (is*)
All is* functions return a boolean and act as TypeScript Type Guards. This means when used in an if statement, TypeScript will automatically narrow the type inside the block.
import { isString, isNumber, isPlainObject, isEmail } from 'typezy';
function processValue(value: unknown) {
if (isString(value)) {
// TypeScript knows `value` is a string here
return value.toUpperCase();
}
if (isNumber(value)) {
// TypeScript knows `value` is a number here
return value.toFixed(2);
}
}
Common Check Functions
| Function | Description |
|---|---|
isString(val) | Checks if value is a string primitive |
isNumber(val) | Checks if value is a finite number (excludes NaN) |
isBoolean(val) | Checks if value is a boolean primitive |
isPlainObject(val) | Checks if value is a plain JavaScript object |
isArray(val) | Checks if value is an Array |
isNonEmptyArray(val) | Checks if value is an array with at least one element |
isNullish(val) | Checks if value is null or undefined |
isDefined(val) | Checks if value is not null and not undefined |
Check the README for the exhaustive list of over 50 type checking functions including formats (UUID, HexColor, JWT) and Environment detections (Browser, Node).
Assertions (assert*)
Assertion functions enforce types at runtime. They throw an AssertionError if the check fails, and narrow the type in TypeScript if it passes.
import { assertString, assertPlainObject, assertEmail, AssertionError } from 'typezy';
function processConfig(config: unknown) {
assertPlainObject(config);
// config is Record<string, unknown>
assertString(config.name, 'Name must be a valid string');
// config.name is string
}
try {
assertEmail('invalid-email', 'Please provide a valid email address');
} catch (error) {
if (error instanceof AssertionError) {
console.error(error.message); // "Please provide a valid email address"
}
}
Form Validation Pattern
Instead of throwing errors, the validation pattern returns a safe result object: { valid: boolean, error?: string }. This is perfect for form validation and UI state.
import { createValidator, validateRequired, validateEmail, validateMinLength, collectErrors } from 'typezy/validate';
// Compose validation rules to fail fast (returns first error)
const validateUsername = createValidator(
validateRequired,
(v) => validateMinLength(v, 3)
);
validateUsername('ab');
// { valid: false, error: 'Must be at least 3 characters' }
validateUsername('alice');
// { valid: true }
// Or collect ALL errors for a field
const errors = collectErrors('x', validateRequired, (v) => validateMinLength(v, 3));
// ['Must be at least 3 characters']
// Validate an entire object against a schema
const schema = {
email: [validateRequired, validateEmail],
age: validateInRange(18, 99)
};
const result = validateSchema({ email: 'hi', age: 10 }, schema);
if (!result.valid) console.log(result.errors);
String Utilities
Safe string manipulation and sanitization.
capitalize(val) / toCamelCase(val) | Case converters |
escapeHtml(val) / stripHtml(val) | XSS protection and HTML cleanup |
slugify(val) | Converts "Hello World!" to "hello-world" |
truncate(val, max, suffix?) | Safely truncates long strings |
Number Utilities
Formatting and math helpers.
import { clamp, formatCurrency, formatCompact } from 'typezy';
clamp(150, 0, 100); // 100
formatCurrency(1234.5, 'USD'); // '$1,234.50'
formatCompact(1500000); // '1.5M'
Environment Variables
Parse and strictly validate Environment Variables at startup (ideal for Next.js/Node config).
import { requireEnv, requireEnvNumber, requireEnvBoolean } from 'typezy';
// Throws cleanly if missing or invalid type
const apiUrl = requireEnv('API_URL');
const port = requireEnvNumber('PORT');
const debug = requireEnvBoolean('DEBUG');
URL & Routing Utils
Safely parse and merge URL params.
import { parseSearchParams, buildQueryString, mergeSearchParams } from 'typezy';
parseSearchParams('https://ex.com?page=1&sort=name');
// { page: '1', sort: 'name' }
mergeSearchParams('https://ex.com?page=1', { page: '2' });
// 'https://ex.com/?page=2'
Async & Error Handling
Go-style error handling and retry logic.
import { tryCatch, timeout, retry } from 'typezy';
// Go-style error handling avoids try/catch block scoping issues
const [user, error] = await tryCatch(fetchUser(id));
if (error) return handleError(error);
// Retry flaky network calls automatically
const result = await retry(() => fetch('/api/flaky'), {
attempts: 3,
delay: 1000,
backoff: true,
});
Frontend Utilities
Essential helpers for UI interactions and timing.
import { debounce, throttle, deepClone, sleep } from 'typezy';
// Debounce expensive search calls
const onSearch = debounce((q) => fetchData(q), 300);
// Throttle UI updates
const onScroll = throttle(() => updateScrollState(), 100);
// Deep clone safely
const copy = deepClone(myNestedObject);
// Async pause
await sleep(1000);
TypeScript Utility Types
Typezy provides powerful generic utility types for advanced TypeScript usage.
DeepPartial<T> | Recursively makes all properties optional |
Brand<T, Name> | Creates a nominal/branded type (e.g., Brand<string, 'UserId'>) |
Prettify<T> | Flattens type intersections to make IDE tooltips readable |
NonEmptyArray<T> | Tuple type guaranteeing at least one element |
UnwrapPromise<T> | Extracts the resolved type from a Promise |