How to Define a Regex-Matched String Type in TypeScript ?
Last Updated :
11 Jul, 2024
Defining a regex-matched string type in TypeScript means creating a type that ensures a string adheres to a specific regular expression pattern. This enhances type safety by validating strings at compile or runtime, ensuring they match predefined formats.
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. In the context of TypeScript or programming in general, a "regex-matched string" means a string that adheres to the specified regex pattern.
Below are the approaches used to define a regex-matched string type in Typescript:
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.
Example: here, we want to create a type RegexMatchedString
that represents a string adhering to a specific regex pattern for a phone number. The template literal type with branding ensures that any string assigned to this type matches the pattern.
JavaScript
type RegexMatchedString<Pattern extends string> =
`${string & { __brand: Pattern }}`;
let validPhoneNumber: RegexMatchedString<"\d{3}-\d{3}-\d{4}"> =
"123-456-7890" as RegexMatchedString<"\d{3}-\d{3}-\d{4}">;
// This will result in a type error because "invalid-number"
// does not match the pattern:
// let invalidPhoneNumber: RegexMatchedString<"\d{3}-\d{3}-\d{4}"> =
// "invalid-number" as RegexMatchedString<"\d{3}-\d{3}-\d{4}">;
console.log(validPhoneNumber);
Output:
"123-456-7890"
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.
Example: here, we want to assert that a string adheres to a specific regex pattern for a hexadecimal color code. The type HexColor
is created using a type assertion function, which checks the pattern at runtime.
JavaScript
type HexColor = string;
function assertHexColor(value: string): asserts value is HexColor {
const hexColorRegex = /^#([0-9a-fA-F]{3}){1,2}$/;
if (!hexColorRegex.test(value)) {
throw new Error(`"${value}" is not a valid hexadecimal color code.`);
}
}
// Example Usage:
let validColor: HexColor = "#1a2b3c";
// The type enforces that the string adheres to
// the specified hexadecimal color code pattern.
// This will result in a runtime error because
// "#invalid" is not a valid color code:
// assertHexColor("#invalid");
console.log(validColor); // Output: #1a2b3c
Output:
#1a2b3c
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.
Example: here, we'll use a template literal type to represent a string adhering to a specific regex pattern for a date in the format "YYYY-MM-DD". The template literal type enforces the pattern at compile time.
JavaScript
type DateString = `${string & { __brand: "\\d{4}-\\d{2}-\\d{2}" }}`;
// Example Usage:
let validDate: DateString = "2022-01-15" as DateString;
// The type enforces that the string adheres
// to the specified date format pattern.
// This will result in a type error because
// "invalid-date" does not match the pattern:
// let invalidDate: DateString = "invalid-date" as DateString;
console.log(validDate); // Output: 2022-01-15
Output:
2022-01-15
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.
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 = "[email protected]" 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:
[email protected]
Similar Reads
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line providing more flexibility. HTML adds Structure to a web page, CSS st
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook created React. Developers with a Javascript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. It is essential for both front-end and back-end developers to have a strong command of
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable. Applications are built using reusable compo
8 min read
REST API Introduction
REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server.
7 min read
HTML Interview Questions and Answers
HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
NodeJS Interview Questions and Answers
NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
What is an API (Application Programming Interface)
In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms. What is an API?An API is a set of
10 min read