To start, you must establish a generic HexType
that utilizes recursive logic within a conditional type:
type HexChar = '0' | '1' | '2' | '3' | '4'
| '5' | '6'| '7' | '8' | '9' | 'A' | 'B' | 'C' | 'D' | 'E' | 'F'
| 'a' | 'b' | 'c' | 'd' | 'e' | 'f';
type HexType<T extends string> = T extends `${infer R1}${infer R2}`
? R1 extends HexChar
? `${R1}${HexType<R2>}`
: never
: `${T}`;
Next, create a function that only accepts values of type HexType
; if the value is not of this type, the argument will be never
:
const MyHexTypeFunction = <T extends string>(value: HexType<T>) => value;
For instance:
const value = MyHexTypeFunction("qxb12"); //results in a type of never and throws an error
const value2 = MyHexTypeFunction("AB234"); //value2 has a type of "AB234"
If you require your Hex string to have an even length, you can implement another generic type and helper function like so:
type HasEvenLegth<T extends string> =
T extends `${infer R1}${infer R2}${infer R3}`
? R3 extends ""
? T
: `${R1}${R2}${HasEvenLegth<R3>}`
: T extends ""
? ""
: never;
const HasEvenLegthFunction = <T extends string>(value: HasEvenLegth<T>) => value;
For example:
const value3 = HasEvenLegthFunction(MyHexTypeFunction("E23a318"));
//results in a type of never and throws an error due to odd length
const value4 = HasEvenLegthFunction(MyHexTypeFunction("EQ"));
//results in a type of never and throws an error due to invalid character
const value5 = HasEvenLegthFunction(MyHexTypeFunction("AbbbB234"));
//value5 is of type "AbbbB234" with no errors
Further information on conditional types can be found here.