I'm trying to write a type that validates that a given input string has valid class names separated by 1 or more whitespace characters. The input may also have leading or trailing whitespace.
The typing I have now is quite close, but the template literal can be inferred by TS compiler in multiple ways, meaning the grammar is ambiguous. This leads to unwanted results.
First we define primitive types:
// To avoid recursion as much as possible
type Spaces = (
| " "
| " "
| " "
| " "
| " "
);
type Whitespace = Spaces | "\n" | "\t";
type ValidClass = 'a-class' | 'b-class' | 'c-class';
Then the utility types
// Utility type to provide nicer error messages
type Err<Message extends string> = `Error: ${Message}`;
type TrimEnd<T extends string> = (
T extends `${infer Rest}${Whitespace}`
? TrimEnd<Rest>
: T
);
type TrimStart<T extends string> = (
T extends `${Whitespace}${infer Rest}`
? TrimStart<Rest>
: T
);
type Trim<T extends string> = TrimEnd<TrimStart<T>>;
and finally the actual type that checks the input string:
// Forces the string to be trimmed before starting recursive loop.
type SplitToValidClasses<T extends string> = SplitToValidClassesInner<Trim<T>>;
// Splits the input string into array of `Array<Token | 'Error: ...'>`
// strings. The input is converted to an array format mostly because I found it
// easier to work with arrays in other TS generics, instead of e.g space separated
// values.
type SplitToValidClassesInner<T extends string> =
// Does `T` contain more than one string? For example 'aaaa\n\n bbbb'
T extends `${infer Head}${Whitespace}${infer Tail}`
// Yes, `T` could be infered into three parts.
// Is `Head` a valid class name?
? Trim<Head> extends ValidClass
// Yes, it's a valid name. Continue recursively with rest of the string
// but trim white space from both sides.
? [Trim<Head>, ...SplitToValidClassesInner<Trim<Tail>>]
: [Err<`'${Head}' is not a valid class`>]
: T extends `${infer Tail}`
? Tail extends ValidClass
? [Tail]
: [Err<`'${Tail}' is not a valid class`>]
: [never];
// This works
type CorrectResult = SplitToValidClasses<'a-class b-class c-class'>
But when testing with different inputs, we can notice incorrect results:
// Should be ["a-class", "b-class", "c-class"]
type Input1 = `a-class b-class c-class`;
type Result = SplitToValidClasses<Input1>;
// Should be ["a-class", "b-class", "c-class", "a-class"]
type Result2 = SplitToValidClasses<`
a-class b-class
c-class
a-class
`>;
// Should be ["a-class", "Error: 'wrong-class' is not a valid class"]
type Result3 = SplitToValidClasses<`
a-class
wrong-class
c-class
`>;
The issue happens in the template inference:
type SplitToValidClassesInnerFirstLevelDebug<T extends string> =
T extends `${infer Head}${Whitespace}${infer Tail}`
? [Head, Whitespace, Tail]
: never
// The grammar is ambiguous, leading to
// "["a-class b-class" | "a-class", Whitespace, "c-class" | "b-class c-class"]
// Removing the ambiguousity should fix the issue
type Result4 = SplitToValidClassesInnerFirstLevelDebug<Input1>
I couldn't find much documentation of the details how template literals are inferred, except what Anders Hejlsberg explained in his PR:
For inference to succeed the starting and ending literal character spans (if any) of the target must exactly match the starting and ending spans of the source. Inference proceeds by matching each placeholder to a substring in the source from left to right: A placeholder followed by a literal character span is matched by inferring zero or more characters from the source until the first occurrence of that literal character span in the source. A placeholder immediately followed by another placeholder is matched by inferring a single character from the source.
How could this typing be achieved, without ambiguous results? One approach I thought of was to recursively parse the input character by character, but it very quickly hits the recursion limit in TS.