CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ts-toolbelt

TypeScript's largest utility library providing 200+ type utilities for advanced type manipulation.

Pending
Overview
Eval results
Files

string.mddocs/

String Module

Template literal-based string manipulation utilities for character access, length calculation, splitting, joining, and replacement operations.

Capabilities

String Access and Properties

Basic string operations for accessing characters and determining string properties.

/**
 * Get character at specific position in string
 * @param S - String to access
 * @param N - Position index (0-based)
 * @returns Character at position N
 */
type At<S extends string, N extends number> = AtImpl<S, N>;

/**
 * Calculate length of string at type level
 * @param S - String to measure
 * @returns Length of string as number literal
 */
type Length<S extends string> = LengthImpl<S>;

Usage Examples:

import { S } from "ts-toolbelt";

// Character access
type FirstChar = S.At<"hello", 0>; // "h"
type ThirdChar = S.At<"world", 2>; // "r"
type LastChar = S.At<"test", 3>; // "t"

// String length
type HelloLength = S.Length<"hello">; // 5
type EmptyLength = S.Length<"">; // 0
type LongLength = S.Length<"typescript">; // 10

// Out of bounds access
type OutOfBounds = S.At<"hi", 5>; // undefined

String Splitting and Joining

Split strings into arrays and join arrays into strings using delimiters.

/**
 * Split string by delimiter into tuple of substrings
 * @param S - String to split
 * @param D - Delimiter to split by
 * @returns Tuple of string parts
 */
type Split<S extends string, D extends string> = S extends `${infer B}${D}${infer A}` 
  ? [B, ...Split<A, D>] 
  : [S];

/**
 * Join array of strings with delimiter
 * @param L - Array of strings to join
 * @param D - Delimiter to join with
 * @returns Single joined string
 */
type Join<L extends readonly string[], D extends string> = JoinImpl<L, D>;

Usage Examples:

import { S } from "ts-toolbelt";

// String splitting
type SplitByDash = S.Split<"hello-world-test", "-">; // ["hello", "world", "test"]
type SplitByDot = S.Split<"a.b.c.d", ".">; // ["a", "b", "c", "d"]
type SplitBySpace = S.Split<"one two three", " ">; // ["one", "two", "three"]
type NoDelimiter = S.Split<"hello", "-">; // ["hello"]
type EmptySplit = S.Split<"", ",">; // [""]

// String joining
type JoinWithDash = S.Join<["hello", "world"], "-">; // "hello-world"
type JoinWithDot = S.Join<["a", "b", "c"], ".">; // "a.b.c"
type JoinEmpty = S.Join<["one", "two"], "">; // "onetwo"
type SingleJoin = S.Join<["hello"], "-">; // "hello"
type EmptyJoin = S.Join<[], ",">; // ""

// Combined operations
type PathParts = S.Split<"users/123/profile", "/">; // ["users", "123", "profile"]
type ReconstructedPath = S.Join<PathParts, "/">; // "users/123/profile"

// URL manipulation
type URL = "https://api.example.com/v1/users";
type URLParts = S.Split<URL, "/">; // ["https:", "", "api.example.com", "v1", "users"]
type Domain = S.Split<URLParts[2], ".">; // ["api", "example", "com"]

String Replacement

Replace occurrences of substrings with new values.

/**
 * Replace all occurrences of substring with replacement
 * @param S - String to perform replacement in
 * @param From - Substring to replace
 * @param To - Replacement substring
 * @returns String with all occurrences replaced
 */
type Replace<S extends string, From extends string, To extends string> = 
  S extends `${infer B}${From}${infer A}` 
    ? `${B}${To}${Replace<A, From, To>}` 
    : S;

Usage Examples:

import { S } from "ts-toolbelt";

// Basic replacement
type ReplaceSpaces = S.Replace<"hello world test", " ", "-">; // "hello-world-test"
type ReplaceVowels = S.Replace<"hello", "o", "0">; // "hell0"
type MultipleReplace = S.Replace<"test test test", "test", "demo">; // "demo demo demo"

// Remove characters (replace with empty string)
type RemoveSpaces = S.Replace<"a b c d", " ", "">; // "abcd"
type RemoveDashes = S.Replace<"phone-number-format", "-", "">; // "phonenumberformat"

// Character escaping
type EscapeQuotes = S.Replace<'say "hello"', '"', '\\"'>; // 'say \\"hello\\"'

// No replacement when pattern not found
type NoMatch = S.Replace<"hello", "xyz", "abc">; // "hello"

// Template processing
type Template = "Hello, {{name}}! Welcome to {{site}}.";
type Step1 = S.Replace<Template, "{{name}}", "John">; // "Hello, John! Welcome to {{site}}."
type Step2 = S.Replace<Step1, "{{site}}", "TypeScript">; // "Hello, John! Welcome to TypeScript."

// File extension changes
type ChangeExtension = S.Replace<"document.txt", ".txt", ".pdf">; // "document.pdf"
type JStoTS = S.Replace<"script.js", ".js", ".ts">; // "script.ts"

// Path normalization
type NormalizePath = S.Replace<"//path//to//file", "//", "/">; // "/path/to/file"

Advanced String Operations

Complex string manipulation patterns combining multiple operations.

Usage Examples:

import { S, L } from "ts-toolbelt";

// Case conversion simulation
type UppercaseA = S.Replace<"hello", "a", "A">;
type UppercaseE = S.Replace<UppercaseA, "e", "E">;
type UppercaseI = S.Replace<UppercaseE, "i", "I">;
// Continue for all vowels...

// String tokenization
type CodeString = "function add(a, b) { return a + b; }";
type Tokenized = S.Split<CodeString, " ">; 
// ["function", "add(a,", "b)", "{", "return", "a", "+", "b;", "}"]

// CSV processing
type CSVRow = "John,Doe,30,Engineer";
type CSVFields = S.Split<CSVRow, ",">; // ["John", "Doe", "30", "Engineer"]
type ReconstructCSV = S.Join<CSVFields, ",">; // "John,Doe,30,Engineer"

// String templating system
type CreateTemplate<Name extends string, Age extends string> = 
  S.Replace<
    S.Replace<"User: {{name}}, Age: {{age}}", "{{name}}", Name>,
    "{{age}}",
    Age
  >;

type UserInfo = CreateTemplate<"Alice", "25">; // "User: Alice, Age: 25"

// Slug generation
type TitleToSlug<T extends string> = 
  S.Replace<
    S.Replace<T, " ", "-">,
    "--",
    "-"
  >;

type BlogSlug = TitleToSlug<"My Great Blog Post">; // "My-Great-Blog-Post"

// Query string parsing
type QueryString = "name=John&age=30&city=NYC";
type QueryPairs = S.Split<QueryString, "&">; // ["name=John", "age=30", "city=NYC"]
type FirstParam = S.Split<QueryPairs[0], "=">; // ["name", "John"]

// File path operations
type FilePath = "/users/documents/file.txt";
type PathSegments = S.Split<FilePath, "/">; // ["", "users", "documents", "file.txt"]
type FileName = PathSegments[3]; // "file.txt"
type FileNameParts = S.Split<FileName, ".">; // ["file", "txt"]
type BaseName = FileNameParts[0]; // "file"
type Extension = FileNameParts[1]; // "txt"

// String validation patterns
type IsValidIdentifier<T extends string> = 
  T extends `${infer First}${infer Rest}`
    ? First extends "a" | "b" | "c" // ... (simplified, would include all valid start chars)
      ? 1
      : 0
    : 0;

type ValidId = IsValidIdentifier<"myVariable">; // 1 (simplified example)
type InvalidId = IsValidIdentifier<"123invalid">; // 0 (simplified example)

Implementation Notes

The String module leverages TypeScript's template literal types introduced in TypeScript 4.1:

  • Template Literal Patterns: Use ${infer} patterns for string parsing
  • Recursive Processing: Recursive types handle multiple occurrences in Replace
  • Character-by-Character Processing: Length and At operations work character by character
  • Delimiter Handling: Split operation handles edge cases like empty strings and missing delimiters

The module provides compile-time string processing that enables powerful string manipulation patterns in TypeScript's type system.

Types

// String operations work with string literal types
// Results are computed at compile time and produce string literal types

Install with Tessl CLI

npx tessl i tessl/npm-ts-toolbelt

docs

any.md

boolean.md

class.md

community.md

function.md

index.md

iteration.md

list.md

misc.md

number.md

object.md

string.md

testing.md

union.md

tile.json