TS Utils Lite

raw JSON →
2.0.31 verified Sat Apr 25 auth: no javascript

ts-utils-lite is a lightweight, type-safe utility library designed for web developers, offering a comprehensive suite of helper functions across various domains. Currently stable at version 2.0.31, the library provides utilities for string manipulation, date formatting and calculations, array operations, object handling (including deep cloning and access), number formatting, robust validation, unique ID generation, cookie management, and both local and session storage interactions. It emphasizes modularity, allowing developers to either import the entire bundle or cherry-pick specific sub-packages (e.g., `ts-string-lite`, `ts-date-lite`) to optimize bundle size. The library is built with TypeScript, ensuring strong type inference and safety, making it an ideal companion for modern JavaScript and TypeScript projects, especially within frameworks like Angular, where its classes can be easily injected.

error TypeError: StringUtils is not a constructor
cause Attempting to call `StringUtils` directly as a function or missing the `new` keyword when it's an instantiable class in a CommonJS context, or if the module resolution is incorrect.
fix
Ensure you are using new StringUtils() or injecting the class correctly. If using CommonJS, confirm the import: const { StringUtils } = require('ts-utils-lite'); const str = new StringUtils();.
error Module not found: Error: Can't resolve 'ts-string-lite' in '...'
cause The specific sub-package was imported but not installed, or the import path is incorrect.
fix
Install the specific sub-package: npm install ts-string-lite or ensure you are importing from the main ts-utils-lite package if you installed that: import { StringUtils } from 'ts-utils-lite';.
error Property 'slugify' does not exist on type 'typeof StringUtils'. Did you mean 'StringUtils'?
cause Attempting to call `StringUtils.slugify()` statically when `slugify` is an instance method (e.g., `new StringUtils().slugify()`).
fix
Create an instance of StringUtils first, then call the method on the instance: const strUtils = new StringUtils(); strUtils.slugify('...');
gotcha The utility functions are exposed via instantiable classes (e.g., `StringUtils`), not static methods on a namespace. Therefore, you must create an instance of the class (e.g., `new StringUtils()`) or inject it in frameworks like Angular to call its methods.
fix Ensure you instantiate the utility class before calling its methods, or use dependency injection if applicable (e.g., `private str: StringUtils`).
gotcha When importing individual sub-packages, the import path is the specific NPM package name (e.g., `ts-string-lite`), not a sub-path of `ts-utils-lite`. Mixing these import styles can lead to module resolution issues.
fix Use `import { StringUtils } from 'ts-string-lite';` for the dedicated string utilities package, and `import { StringUtils } from 'ts-utils-lite';` for the aggregated bundle.
gotcha CookieUtils and StorageUtils are designed for browser environments. Attempting to use them in a Node.js environment (e.g., server-side rendering without proper polyfills) will result in runtime errors due to undefined `document` or `localStorage` objects.
fix Wrap usage of `CookieUtils` and `StorageUtils` with checks for `typeof document !== 'undefined'` or `typeof localStorage !== 'undefined'` to ensure they only execute in browser contexts.
breaking Like many modern TypeScript libraries, `ts-utils-lite` likely transitioned to an ESM-first approach in its major versions (e.g., v2.x). Direct `require()` statements might not work correctly without proper CommonJS interoperability configuration.
fix Prefer ES Module imports (`import { ... } from '...'`). If using CommonJS, ensure your build setup (e.g., Webpack, Rollup) or Node.js environment is configured to correctly handle ESM modules. You might need to adjust `tsconfig.json` (`"module": "Node16"` or `"ESNext"`) and `package.json` (`"type": "module"`).
npm install ts-utils-lite
yarn add ts-utils-lite
pnpm add ts-utils-lite

This example demonstrates how to use `ts-utils-lite` within an Angular service, showcasing the instantiation and usage of various utility classes like StringUtils, DateUtils, ArrayUtils, ObjectUtils, ValidationUtils, and others, including environment-dependent Cookie and Storage utilities.

import { Injectable } from '@angular/core';
import {
  StringUtils,
  DateUtils,
  ArrayUtils,
  ObjectUtils,
  NumberUtils,
  ValidationUtils,
  IdUtils,
  CookieUtils,
  StorageUtils
} from 'ts-utils-lite';

@Injectable({ providedIn: 'root' })
export class MyService {
  constructor(
    private str: StringUtils,
    private date: DateUtils,
    private arr: ArrayUtils,
    private obj: ObjectUtils,
    private num: NumberUtils,
    private val: ValidationUtils,
    private id: IdUtils,
    private cookie: CookieUtils,
    private storage: StorageUtils
  ) { }
  
  runExamples(): void {
    // String Utils
    console.log('Slugify:', this.str.slugify('Hello World Example'));       // 'hello-world-example'
    
    // Date Utils
    console.log('Formatted Date:', this.date.format(new Date(), 'YYYY-MM-DD')); // e.g., '2026-04-24'
    
    // Array Utils
    console.log('Unique Array:', this.arr.unique([1, 2, 2, 3, 1]));         // [1, 2, 3]
    
    // Object Utils
    console.log('Deep Get:', this.obj.deepGet({a: {b: 42}}, 'a.b')); // 42
    
    // Number Utils
    console.log('Formatted Currency:', this.num.formatCurrency(1234.56));      // '$1,234.56'
    
    // Validation Utils
    console.log('Is Email:', this.val.isEmail('test@example.com'));  // true
    
    // ID Utils
    console.log('Generated UUID:', this.id.uuid());                        // e.g., '550e8400-e29b-41d4-a716-446655440000'
    
    // Cookie Utils (requires browser environment)
    if (typeof document !== 'undefined') {
      this.cookie.set('theme', 'dark', 7);   // Set cookie for 7 days
      console.log('Cookie "theme":', this.cookie.get('theme'));
    }
    
    // Storage Utils (requires browser environment)
    if (typeof localStorage !== 'undefined') {
      this.storage.set('user', { name: 'John Doe', id: 123 }); // Set to localStorage
      const user = this.storage.get('user');      // Get from localStorage
      console.log('Stored User:', user);
      this.storage.remove('user'); // Clean up
    }
  }
}