Categories
TypeScript Answers

How to define a regex-matched string type in TypeScript?

Spread the love

Sometimes, we want to define a regex-matched string type in TypeScript.

In this article, we’ll look at how to define a regex-matched string type in TypeScript.

How to define a regex-matched string type in TypeScript?

To define a regex-matched string type in TypeScript, we can create a literal type that matches the pattern of a given string.

For instance, we write

type MarkerTime = `${number | ""}${number}:${number}${number}`;
const t: MarkerTime = "09:00";

to create the MarkerTime type which is type that matches a string with 1 to 2 numbers before the colon and 2 numbers after.

Therefore, we can create a MarkTime variable t with value "09:00" and the TypeScript compiler will accept it.

Conclusion

To define a regex-matched string type in TypeScript, we can create a literal type that matches the pattern of a given string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *