typescript / expert
Snippet
Recursive Template Literal Syntax Validation at Type Compile-Time
Template literal types can parse and validate structured DSL strings purely at compile time. By recursively extracting character segments using infer, TypeScript validates lexical rules without incurring runtime memory allocations.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
type ValidIdentifier<S extends string> =S extends `${infer First}${infer Rest}`? First extends 'a'|'b'|'c'|'d'|'e'|'f'|'g'|'h'|'i'|'j'|'k'|'l'|'m'|'n'|'o'|'p'|'q'|'r'|'s'|'t'|'u'|'v'|'w'|'x'|'y'|'z'? ValidIdentifier<Rest> extends true ? true : false: false: true;type StrictSqlQuery<T extends string> =T extends `SELECT ${infer Cols} FROM ${infer Table}`? ValidIdentifier<Table> extends true? { table: Table; columns: Cols }: never: never;type Parsed = StrictSqlQuery<"SELECT id FROM users">;
Breakdown
1
S extends `${infer First}${infer Rest}`
Splits a template literal string into its head character (First) and remaining tail (Rest).
2
First extends 'a'|'b'|...|'z'
Checks whether the extracted head character satisfies the identifier character set constraint.
3
T extends `SELECT ${infer Cols} FROM ${infer Table}`
Pattern matches a string literal against an expected SQL statement structure.
4
type Parsed = StrictSqlQuery<"SELECT id FROM users">;
Evaluates to an object type `{ table: "users"; columns: "id" }` at compile-time.