79448130

Date: 2025-02-18 11:47:48
Score: 3
Natty:
Report link

You could try using Regex to 'test' the string, since this falls into that category.

type BinaryString = `${string & { __brand: "{0|1}*" }}`;

function assertBinaryString(value: string): BinaryString {
    const binaryRegex = /^[01]*$/;
    if (binaryRegex.test(value)) {
        return value as BinaryString;
    } else {
        throw new Error("Invalid binary string format");
    }
}

let validDate: BinaryString = assertBinaryString("010101");
console.log(validDate); // Output : 010101
let invalidDate: BinaryString = assertBinaryString("random");
console.log(invalidDate) // Output : Error

Source: How to Define a Regex-Matched String Type in TypeScript ?

Reasons:
  • Probably link only (1):
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Low reputation (1):
Posted by: Nithika Dias