Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – type to check if the string contains only specific characters

How to have type check for strings that we know will contains only certain values.
Example: const binary = '1010000101000'; We know that binary values represented in decimal would only be 1’s & 0’s. To have a better type check, what would be a good type definition for these kinds of values.

type Binary = '0' | '1'; wouldn’t work, because these would be representing only single characters of the string. But the idea is how to have an interface/type for the whole string that we know would contain only certain types of characters in a string.

The question is not about choosing interface for binary values, it’s how to declare/define types for predefined string values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a recursive typing :

type BinDigit = "0" | "1"

type OnlyBinDigit<S> =
    S extends ""
        ? unknown
        : S extends `${BinDigit}${infer Tail}`
            ? OnlyBinDigit<Tail>
            : never




function onlyBinDigit<S extends string>(s: S & OnlyBinDigit<S>) {
}



onlyBinDigit("01010101010011"); // OK 
onlyBinDigit("010101012"); // NOK

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading