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.

JavaScript
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.

Similar Reads

Approach 1: Template Literal Types with Branding

This approach uses template literal types along with a branding technique to create a branded string type that matches a specific regex pattern....

Approach 2: Type Assertion with Function

This approach involves using a type assertion function to ensure that a string matches a given regex pattern at runtime....

Approach 3: Template Literal Types Only

This approach relies solely on template literal types without additional runtime functions. It uses the ${string & { __brand: Pattern }} template literal type....

Approach 4: Using Regular Expression Objects

In this approach, we directly use regular expression objects to define a type that represents a string matching a specific regular expression....

Contact Us