How to useRegular Expression Objects in Typescript
In this approach, we directly use regular expression objects to define a type that represents a string matching a specific regular expression.
Syntax:
type RegexMatchedString<Pattern extends RegExp> = string & { __regexPattern: Pattern };
Example: Below is the implementation of the above-discussed approach.
type RegexMatchedString<Pattern extends RegExp> = string & { __regexPattern: Pattern };
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
type Email = RegexMatchedString<typeof emailRegex>;
function assertMatchesPattern(value: string, pattern: RegExp): asserts value is RegexMatchedString<typeof pattern> {
if (!pattern.test(value)) {
throw new Error(`"${value}" does not match the specified pattern.`);
}
}
const validEmail: Email = "nikunj.sonigara@gfg.com" as Email;
// The type enforces that the string adheres to
// the specified email pattern.
// This will result in a runtime error because
// "invalid-email" does not match the pattern:
// assertMatchesPattern("invalid-email", emailRegex);
console.log(validEmail); // Output: nikunj.sonigara@gfg.com
Output:
nikunj.sonigara@gfg.com
How to Define a Regex-Matched String Type in TypeScript ?
In TypeScript, you can define a type that represents a string matching a specific regular expression using different approaches.
Below are the approaches used to define a regex-matched string type in Typescript:
Table of Content
- Template Literal Types with Branding
- Type Assertion with Function
- Template Literal Types Only
- Using Regular Expression Objects
What is a regex-matched string?
A “regex-matched string” refers to a string that satisfies a specific pattern or regular expression (regex). A regular expression is a sequence of characters that defines a search pattern. When we talk about a “regex-matched string” in the context of TypeScript or programming in general, it means a string that adheres to the specified regex pattern.
Contact Us