I have a list of characters "gbiusor" that are style formatting for jQuery Terminal. And I want to create a TypeScript type that will be a string with any combination of the above characters. It can have one element or all of them. The characters can be duplicated, but if it's possible to make it unique, that's even better.
I was asking ChatGPT, it was giving me garbage (as always) but one of the answers seems reasonable:
type FormattingStyle = '' | `${'g' | 'b' | 'i' | 'u' | 's' | 'o' | 'r'}${FormattingStyle}`;
const style: FormattingStyle = 'gb';
The problem, it gives an error:
Type alias 'FormattingStyle' circularly references itself.
I'm not sure how to refactor that code to get rid of circular reference, and I'm not sure what approach should I take. When I asked chatGPT about the error he given me this:
type FormattingChar = 'g' | 'b' | 'i' | 'u' | 's' | 'o' | 'r';
type FormattingStyle = ''
| FormattingChar
| `${FormattingChar}${FormattingChar}`
| `${FormattingChar}${FormattingChar}${FormattingChar}`
| `${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}`
| `${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}`
| `${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}`
| `${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}${FormattingChar}`;
This gives error:
Expression produces a union type that is too complex to represent.
Can't you just use a recursive string type in TypeScript?
FormattingChar, you can just barely get TS to compute the full union of all possible valid strings without duplicates. Unions can hold up to about 100K members maximum, and this one is in the 10K range. One more character would break it, and even a 10K member union is going to slow down TS if you use it a lot. Less intense is to just make TS check a candidate with a helper function. Both approaches are shown in this playground link. Does that fully address the question? If so I'll write an answer or find a duplicate; if not, what's missing?StringSetsince this what the type is doing.