Type-level string parsing
Concept and syntax
Recursive template matching can split a literal string at delimiters, accumulating a tuple of segments. Stop when no delimiter remains. This grammar preserves empty segments, handles only literal strings precisely and is not a runtime split function.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Split<S extends string>=string extends S?string[]:S extends `${infer H}/${infer R}`?[H,...Split<R>]:[S]; type P=Split<"a//b">;const p:P=["a","","b"]; console.log(JSON.stringify(p));Expected output:
["a","","b"]Common mistake
Intentionally invalid; compile separately and do not execute.
type Split<S extends string>=string extends S?string[]:S extends `${infer H}/${infer R}`?[H,...Split<R>]:[S]; type P=Split<"a//b">;const p:P=["a","b"];Expected diagnostic: TS2322. The consecutive delimiters create an empty middle segment.
Practice and recap
Test a trailing delimiter and a broad string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Type-level string parsing — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Type-level string parsing is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Split<S extends string>=string extends S?string[]:S extends `${infer H}/${infer R}`?[H,...Split<R>]:[S]; type P=Split<"a//b">;const p:P=["a","","b"]; console.log(JSON.stringify(p));Which diagnostic and explanation match the rejected example under the lesson settings?
type Split<S extends string>=string extends S?string[]:S extends `${infer H}/${infer R}`?[H,...Split<R>]:[S]; type P=Split<"a//b">;const p:P=["a","b"];What is Split<"a/">?