Home > Net >  Typescript - type to check if the string contains only specific characters
Typescript - type to check if the string contains only specific characters

Time:07-10

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.

CodePudding user response:

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

  • Related