v0.7.0 - Branded Types for TypeScript
🎉 Branded Types for Compile-Time Type Safety
This release introduces branded types to nano-string-utils, providing compile-time type safety for validated strings in TypeScript applications with zero runtime overhead.
✨ What's New
Branded Types System
- New
brandednamespace export containing all branded type utilities - Three core branded types:
Email,URL, andSlug - Generic
Brand<K, T>utility for creating custom branded types
15 New Functions
Type Guards - Runtime validation with type narrowing:
isValidEmail()- Validates and narrows to Email typeisValidUrl()- Validates and narrows to URL typeisSlug()- Validates and narrows to Slug type
Builder Functions - Safe construction with validation:
toEmail()- ReturnsEmail | nulltoUrl()- ReturnsURL | nulltoSlug()- Always returnsSlug(transforms input)
Assertion Functions - Runtime assertions with type narrowing:
assertEmail()- ThrowsBrandedTypeErrorif invalidassertUrl()- ThrowsBrandedTypeErrorif invalidassertSlug()- ThrowsBrandedTypeErrorif invalid
Unsafe Variants - For trusted inputs:
unsafeEmail()- Direct cast without validationunsafeUrl()- Direct cast without validationunsafeSlug()- Direct cast without validation
Utilities:
ensureSlug()- Intelligently handles existing slugs or transforms new onesBrandedTypeError- Custom error class for validation failures
📊 Performance & Size
- Zero runtime overhead - Types are completely erased at compilation
- Tree-shakeable - Only imported when explicitly used
- Bundle size - Remains under 6.5KB limit (6.35KB CJS)
- Type guards - Identical performance to base validators
- Unsafe variants - ~18M ops/sec (simple type casts)
📖 Example Usage
```typescript
import { branded } from 'nano-string-utils';
// Type-safe email handling
const email = branded.toEmail('[email protected]');
if (email) {
sendNewsletter(email); // email is typed as Email
}
// Assertion-based validation
const input = getUserInput();
branded.assertEmail(input);
// input is now typed as Email
sendEmail(input);
// Type guards for narrowing
if (branded.isValidUrl(input)) {
// input is now typed as URL
fetch(input);
}
```
📦 Installation
```bash
npm install [email protected]
or
yarn add [email protected]
or
pnpm add [email protected]
```
🧪 Testing
- 100% test coverage including type-level tests
- 5 new test suites with 893 total passing tests
- Performance benchmarks confirming no degradation
📚 Documentation
Full documentation and examples available in the README
Full Changelog: v0.6.0...v0.7.0