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