or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

any.mdboolean.mdclass.mdcommunity.mdfunction.mdindex.mditeration.mdlist.mdmisc.mdnumber.mdobject.mdstring.mdtesting.mdunion.md

string.mddocs/

0

# String Module

1

2

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

3

4

## Capabilities

5

6

### String Access and Properties

7

8

Basic string operations for accessing characters and determining string properties.

9

10

```typescript { .api }

11

/**

12

* Get character at specific position in string

13

* @param S - String to access

14

* @param N - Position index (0-based)

15

* @returns Character at position N

16

*/

17

type At<S extends string, N extends number> = AtImpl<S, N>;

18

19

/**

20

* Calculate length of string at type level

21

* @param S - String to measure

22

* @returns Length of string as number literal

23

*/

24

type Length<S extends string> = LengthImpl<S>;

25

```

26

27

**Usage Examples:**

28

29

```typescript

30

import { S } from "ts-toolbelt";

31

32

// Character access

33

type FirstChar = S.At<"hello", 0>; // "h"

34

type ThirdChar = S.At<"world", 2>; // "r"

35

type LastChar = S.At<"test", 3>; // "t"

36

37

// String length

38

type HelloLength = S.Length<"hello">; // 5

39

type EmptyLength = S.Length<"">; // 0

40

type LongLength = S.Length<"typescript">; // 10

41

42

// Out of bounds access

43

type OutOfBounds = S.At<"hi", 5>; // undefined

44

```

45

46

### String Splitting and Joining

47

48

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

49

50

```typescript { .api }

51

/**

52

* Split string by delimiter into tuple of substrings

53

* @param S - String to split

54

* @param D - Delimiter to split by

55

* @returns Tuple of string parts

56

*/

57

type Split<S extends string, D extends string> = S extends `${infer B}${D}${infer A}`

58

? [B, ...Split<A, D>]

59

: [S];

60

61

/**

62

* Join array of strings with delimiter

63

* @param L - Array of strings to join

64

* @param D - Delimiter to join with

65

* @returns Single joined string

66

*/

67

type Join<L extends readonly string[], D extends string> = JoinImpl<L, D>;

68

```

69

70

**Usage Examples:**

71

72

```typescript

73

import { S } from "ts-toolbelt";

74

75

// String splitting

76

type SplitByDash = S.Split<"hello-world-test", "-">; // ["hello", "world", "test"]

77

type SplitByDot = S.Split<"a.b.c.d", ".">; // ["a", "b", "c", "d"]

78

type SplitBySpace = S.Split<"one two three", " ">; // ["one", "two", "three"]

79

type NoDelimiter = S.Split<"hello", "-">; // ["hello"]

80

type EmptySplit = S.Split<"", ",">; // [""]

81

82

// String joining

83

type JoinWithDash = S.Join<["hello", "world"], "-">; // "hello-world"

84

type JoinWithDot = S.Join<["a", "b", "c"], ".">; // "a.b.c"

85

type JoinEmpty = S.Join<["one", "two"], "">; // "onetwo"

86

type SingleJoin = S.Join<["hello"], "-">; // "hello"

87

type EmptyJoin = S.Join<[], ",">; // ""

88

89

// Combined operations

90

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

91

type ReconstructedPath = S.Join<PathParts, "/">; // "users/123/profile"

92

93

// URL manipulation

94

type URL = "https://api.example.com/v1/users";

95

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

96

type Domain = S.Split<URLParts[2], ".">; // ["api", "example", "com"]

97

```

98

99

### String Replacement

100

101

Replace occurrences of substrings with new values.

102

103

```typescript { .api }

104

/**

105

* Replace all occurrences of substring with replacement

106

* @param S - String to perform replacement in

107

* @param From - Substring to replace

108

* @param To - Replacement substring

109

* @returns String with all occurrences replaced

110

*/

111

type Replace<S extends string, From extends string, To extends string> =

112

S extends `${infer B}${From}${infer A}`

113

? `${B}${To}${Replace<A, From, To>}`

114

: S;

115

```

116

117

**Usage Examples:**

118

119

```typescript

120

import { S } from "ts-toolbelt";

121

122

// Basic replacement

123

type ReplaceSpaces = S.Replace<"hello world test", " ", "-">; // "hello-world-test"

124

type ReplaceVowels = S.Replace<"hello", "o", "0">; // "hell0"

125

type MultipleReplace = S.Replace<"test test test", "test", "demo">; // "demo demo demo"

126

127

// Remove characters (replace with empty string)

128

type RemoveSpaces = S.Replace<"a b c d", " ", "">; // "abcd"

129

type RemoveDashes = S.Replace<"phone-number-format", "-", "">; // "phonenumberformat"

130

131

// Character escaping

132

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

133

134

// No replacement when pattern not found

135

type NoMatch = S.Replace<"hello", "xyz", "abc">; // "hello"

136

137

// Template processing

138

type Template = "Hello, {{name}}! Welcome to {{site}}.";

139

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

140

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

141

142

// File extension changes

143

type ChangeExtension = S.Replace<"document.txt", ".txt", ".pdf">; // "document.pdf"

144

type JStoTS = S.Replace<"script.js", ".js", ".ts">; // "script.ts"

145

146

// Path normalization

147

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

148

```

149

150

### Advanced String Operations

151

152

Complex string manipulation patterns combining multiple operations.

153

154

**Usage Examples:**

155

156

```typescript

157

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

158

159

// Case conversion simulation

160

type UppercaseA = S.Replace<"hello", "a", "A">;

161

type UppercaseE = S.Replace<UppercaseA, "e", "E">;

162

type UppercaseI = S.Replace<UppercaseE, "i", "I">;

163

// Continue for all vowels...

164

165

// String tokenization

166

type CodeString = "function add(a, b) { return a + b; }";

167

type Tokenized = S.Split<CodeString, " ">;

168

// ["function", "add(a,", "b)", "{", "return", "a", "+", "b;", "}"]

169

170

// CSV processing

171

type CSVRow = "John,Doe,30,Engineer";

172

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

173

type ReconstructCSV = S.Join<CSVFields, ",">; // "John,Doe,30,Engineer"

174

175

// String templating system

176

type CreateTemplate<Name extends string, Age extends string> =

177

S.Replace<

178

S.Replace<"User: {{name}}, Age: {{age}}", "{{name}}", Name>,

179

"{{age}}",

180

Age

181

>;

182

183

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

184

185

// Slug generation

186

type TitleToSlug<T extends string> =

187

S.Replace<

188

S.Replace<T, " ", "-">,

189

"--",

190

"-"

191

>;

192

193

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

194

195

// Query string parsing

196

type QueryString = "name=John&age=30&city=NYC";

197

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

198

type FirstParam = S.Split<QueryPairs[0], "=">; // ["name", "John"]

199

200

// File path operations

201

type FilePath = "/users/documents/file.txt";

202

type PathSegments = S.Split<FilePath, "/">; // ["", "users", "documents", "file.txt"]

203

type FileName = PathSegments[3]; // "file.txt"

204

type FileNameParts = S.Split<FileName, ".">; // ["file", "txt"]

205

type BaseName = FileNameParts[0]; // "file"

206

type Extension = FileNameParts[1]; // "txt"

207

208

// String validation patterns

209

type IsValidIdentifier<T extends string> =

210

T extends `${infer First}${infer Rest}`

211

? First extends "a" | "b" | "c" // ... (simplified, would include all valid start chars)

212

? 1

213

: 0

214

: 0;

215

216

type ValidId = IsValidIdentifier<"myVariable">; // 1 (simplified example)

217

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

218

```

219

220

## Implementation Notes

221

222

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

223

224

- **Template Literal Patterns**: Use `${infer}` patterns for string parsing

225

- **Recursive Processing**: Recursive types handle multiple occurrences in Replace

226

- **Character-by-Character Processing**: Length and At operations work character by character

227

- **Delimiter Handling**: Split operation handles edge cases like empty strings and missing delimiters

228

229

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

230

231

## Types

232

233

```typescript { .api }

234

// String operations work with string literal types

235

// Results are computed at compile time and produce string literal types

236

```