1 | initial version |
You can use a type parameter with a union type and constraint it to a string literal type that matches the template string using a template literal type. Here is an example:
type TemplateString<T extends `${string} ${string}`> = T;
type AllowedValues = TemplateString<'hello world'> | TemplateString<'goodbye moon'>;
function someFunction(value: AllowedValues) {
// ...
}
// OK
someFunction('hello world');
// OK
someFunction('goodbye moon');
// Error: Type '"foo bar"' is not assignable to type 'AllowedValues'.
someFunction('foo bar');
In this example, the TemplateString
type is defined with a type parameter T
that is constrained to a string literal type using a template literal type ${string} ${string}
. This means that T
can only be a string literal type that consists of two words separated by a space.
The AllowedValues
type is then defined as a union type of two TemplateString
types that comply with the template string constraint. The someFunction
function takes an argument of type AllowedValues
, which means that it can only accept values that match either 'hello world'
or 'goodbye moon'
.
If you try to pass a value that does not comply with the template string constraint, like 'foo bar'
, you will get a type error.