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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-02-05 11:00:00 +0000
Seen: 8 times
Last updated: Jul 30 '22
How can one ensure that sub-classes have uniform method parameters in TypeScript?
Can a TypeScript definition for icon names be provided in MaterialCommunityIcons for React Native?
How can TypeScript be used to save a file in an Excel add-in?
What is the Angular Type script NG Zorro event for radio buttons?
What is the process for implementing a Many to Many relationship using NestJs Sequlize and Mysql2?
What is the method for defining a Fixed length Array in TypeScript?
What difficulties are encountered in the installation of react-router-dom using typescript?