-
Notifications
You must be signed in to change notification settings - Fork 13k
Description
Suggestion
Template literal types seem to be resolved immediately, which makes the combinatorics blow up and the whole thing much less useful than it would seem to be at first.
For example I can't even represent a type equals to 5 consecutive digits with the current system without getting a "too complex" error:
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type UUID = `${Digit}${Digit}${Digit}${Digit}${Digit}`;
The current system may be more composable than regexes, but if it's not even able to represent something like /\d{5}/
I'd argue that's not a replacement for it at all.
The suggestion is that there's no need to resolve all the possible combinations at all, but a divide and conquer approach should be implemented where each little piece of the template literal does it's job individually and when all little pieces match than the whole thing matches.
🔍 Search Terms
- template literal
- lazy
✅ Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
Evaluate template literal types lazily to not make the combinatorics blow up. Meaning that each little piece of the template literal should be its own little function that performs some type matching internally, so there's no need to resolve all the possible combinations at all.
📃 Motivating Example
I can't even represent the equivalent of /\d{5}/
currently.
type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type UUID = `${Digit}${Digit}${Digit}${Digit}${Digit}`;
💻 Use Cases
For example creating a type for UUID strings, which are a fairly common thing.