Skip to content

v0.7.0 - Branded Types for TypeScript

Choose a tag to compare

@Zheruel Zheruel released this 06 Sep 16:57
· 51 commits to main since this release
e4fc662

🎉 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 branded namespace export containing all branded type utilities
  • Three core branded types: Email, URL, and Slug
  • 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 type
  • isValidUrl() - Validates and narrows to URL type
  • isSlug() - Validates and narrows to Slug type

Builder Functions - Safe construction with validation:

  • toEmail() - Returns Email | null
  • toUrl() - Returns URL | null
  • toSlug() - Always returns Slug (transforms input)

Assertion Functions - Runtime assertions with type narrowing:

  • assertEmail() - Throws BrandedTypeError if invalid
  • assertUrl() - Throws BrandedTypeError if invalid
  • assertSlug() - Throws BrandedTypeError if invalid

Unsafe Variants - For trusted inputs:

  • unsafeEmail() - Direct cast without validation
  • unsafeUrl() - Direct cast without validation
  • unsafeSlug() - Direct cast without validation

Utilities:

  • ensureSlug() - Intelligently handles existing slugs or transforms new ones
  • BrandedTypeError - 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