Ask Your Question
0

What is the method to limit the typescript union to only accept values that comply with a template string?

asked 2023-02-05 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-07-30 13:00:00 +0000

lakamha gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-02-05 11:00:00 +0000

Seen: 8 times

Last updated: Jul 30 '22