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