string-ts

repository·main·Indexed 23 days ago

https://github.com/gustavoguichard/string-ts

A library of strongly-typed string manipulation functions for TypeScript v5+ that preserve literal type information at both the type and runtime levels. It provides type-safe counterparts to native String.prototype methods (such as replace, slice, and split), casing utilities (camelCase, snake_case, etc.), and tools for shallow or deep transformation of object keys. The library also allows overriding native String.prototype type declarations via 'string-ts/native' for project-wide strong typing.

Tokens
6.4K
Snippets
38
Records
56
Agent score
77%

What's inside string-ts

  1. How string-ts provides strongly-typed string transformations

    main

    Standard JavaScript string methods (like .replace()) only operate at runtime, causing TypeScript to lose specific literal type information and fall back to the generic string type.

    string-ts provides utility functions that perform the same operations at runtime while preserving literal types (and unions of literals) at the type level. This allows for better static analysis and prevents errors that would otherwise only be caught at runtime.

    import { replace } from 'string-ts'
    
    const str = 'hello-world'
    const result = replace(str, '-', ' ')
    //    ^ 'hello world'
  2. How string-ts preserves literal types

    main

    Standard JavaScript string methods (like String.prototype.replace) operate only at runtime and cause TypeScript to widen the type to a generic string.

    string-ts provides counterparts that operate at both the runtime and the type level. When you use a string-ts function on a string literal, the resulting type reflects the specific transformation, preventing accidental type widening.

    Comparison

    Standard Method (Type Widening):

    const str = 'hello-world'
    const result = str.replace('-', ' ') // result type is 'string'

    string-ts Method (Type Preservation):

    import { replace } from 'string-ts'
    const str = 'hello-world'
    const result = replace(str, '-', ' ')
    // result type is 'hello world'
    import { replace } from 'string-ts'
    const str = 'hello-world'
    const result = replace(str, '-', ' ')
    //    ^ 'hello world'
  3. Override native String.prototype with strongly-typed methods

    main

    If you prefer using native string methods (e.g., str.replace()) instead of importing individual functions, you can override the String.prototype type declarations project-wide by importing string-ts/native.

    This gives you strong typing for supported methods like charAt, startsWith, endsWith, replace, split, and more, with minimal impact on TypeScript compiler performance.

    Note: Only methods already implemented in the library are typed. The length property cannot be strongly-typed as it is a read-only property, not a method.

    import 'string-ts/native'
    
    const str = 'hello-world' as const
    
    str.replace('-', '_')
    //  ^? 'hello_world'
    
    str.charAt(6)
    //  ^? 'w'
    
    str.startsWith('hello')
    //  ^? true
    
    str.split('-')
    //  ^? ['hello', 'world']
  4. Install string-ts via npm

    main

    To use string-ts in your project, install it using npm:

    npm install string-ts

    Note that string-ts requires TypeScript v5+ to function correctly. The library is designed to be tree-shakeable and works with modern build tools like Webpack, Vite, and Rollup.

  5. Known limitations of string-ts

    main

    When using string-ts, be aware of the following constraints:

    ASCII only

    string-ts is designed for common ASCII characters. It does not currently support international characters or emojis.

    Type-level recursion depth

    Because some types rely on TypeScript recursion, very large inputs may exceed TypeScript's internal evaluation limits. When this happens, the inferred type will widen to a generic string pattern, but the runtime behavior remains unaffected.

    Function / TypeExact-literal limitBehaviour beyond limit
    repeat / Repeatcount ≤ 45Returns string
    padStart / PadStartpadding ≤ 45 charsReturns `${string}<original>`
    padEnd / PadEndpadding ≤ 45 charsReturns `<original>${string}`
  6. Deeply transform object keys at runtime only

    main

    The deepTransformKeys function allows you to recursively transform object keys using a provided transformation function at runtime. Note that this does not automatically update the TypeScript types; you must manually cast the result if you need type safety.

    import { deepTransformKeys, toUpperCase } from 'string-ts'
    
    const data = { helloWorld: 'baz' } as const
    
    type MyType<T> = { [K in keyof T as Uppercase<K>]: T[K] }
    const result = deepTransformKeys(data, toUpperCase) as MyType<typeof data>
    //    ^ { 'HELLOWORLD': 'baz' }
  7. Convert strings to various casing formats

    main
    Use these functions to convert strings to specific casing formats at both runtime and type levels. Note that lowerCase and upperCase split by words and join with a space, unlike the native toLowerCase and toUpperCase methods.
  8. Convert strings between word casings

    main

    The library provides utilities to convert strings between different casing conventions. Most utilities export both a transformation function (e.g., camelCase) and a type helper (e.g., CamelCase).

    Supported Casings

    • camelCase / toCamelCase
    • constantCase / toConstantCase
    • delimiterCase / toDelimiterCase
    • kebabCase / toKebabCase
    • pascalCase / toPascalCase
    • snakeCase / toSnakeCase
    • titleCase / toTitleCase

    Other Word Utilities

    • capitalize: Capitalizes the first letter.
    • uncapitalize: Removes capitalization from the first letter.
    • lowerCase: Converts string to lower case.
    • upperCase: Converts string to upper case.
    • words: Splits a string into an array of words.
    • reverse: Reverses the characters in a string.
    • truncate: Truncates a string to a specific length.
  9. Convert strings to snake_case with snakeCase()

    main

    The snakeCase function transforms a string into snake_case at both the runtime and type levels. It performs the following transformations:

    1. Removes apostrophes.
    2. Replaces delimiters with underscores (_).
    3. Converts the entire string to lowercase.

    Because it is strongly typed, the resulting TypeScript type will reflect the exact snake_case transformation of the input literal string.

    Note: toSnakeCase is deprecated. Use snakeCase instead.

    snakeCase('hello world') // 'hello_world'