Typescript 4.3.4 Update
You can now use string template literal types to define a pattern like:
type S = 'cool' | 'wow' | 'biz' | 'sweet' | 'yowza' | 'fantastic';
type Test = `${S},${S}`
What you still can't do is make this infinitely extensible, like an array. To make this work typescript generates every single combination as a union. But for small lists like this it can work.
For example:
type S = 'cool' | 'wow' | 'biz' | 'sweet' | 'yowza' | 'fantastic';
type Amaze =
| `${S}`
| `${S},${S}`
| `${S},${S},${S}`
| `${S},${S},${S},${S}`
| `${S},${S},${S},${S},${S}`
| `${S},${S},${S},${S},${S},${S}`
If you hover over Amaze
, you will see the type reported as:
type Amaze = S | "cool,cool" | "cool,wow" | "cool,biz" | "cool,sweet"
| "cool,yowza" | "cool,fantastic" | "wow,cool" | "wow,wow"
| "wow,biz" | "wow,sweet" | "wow,yowza" | "wow,fantastic"
| ... 55967 more ...| "fantastic,fantastic,fantastic,fantastic,fantastic,fantastic"
See typescript playground
Notice that ... 55967 more ...
. Amaze is now a union with over fifty five thousand possible values. This may affect performance in your IDE at this point. And if you add the version that takes 7 strings you'll get a type error:
Expression produces a union type that is too complex to represent.(2590)
Eventually typescript cuts you off for performance sake. But again, for small lists, this may be viable.
Original answer: Typescript 3.7
You can't.
Typescript can type string
s which can have any content, or can it can type exact strings like "cool"
or "wow"
. But typescript will never know about if a string contains certain characters.
The only way to make this work would be to store these as an array instead:
type AmazeArray = AcceptableVal[];
const dabes: AmazeArray = ['cool', 'wow'];