Why doesn't this type for GUID in TypeScript behave as expected?

102 Views Asked by At

I am trying to make a type for GUID in TypeScript and while this looks like it should enforce hex strings divided with "-", it does not.


type GUID = `${HexString<8>}-${HexString<4>}-${HexString<4>}-${HexString<4>}-${HexString<12>}`;

type HexString<N extends number> = string & {
  readonly length: N;
} & (LowercaseLettersOnly<string> | DigitOnly<string>);

type LowercaseLettersOnly<T extends string> = T extends `${infer U}${infer R}` ? (U extends LowercaseLetter ? LowercaseLettersOnly<R> : never) : T;

type LowercaseLetter = 'a' | 'b' | 'c' | 'd' | 'e' | 'f';
type DigitOnly<T extends string> = T extends `${infer U}${infer R}` ? (U extends Digit ? DigitOnly<R> : never) : T;

type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f';


Expected to throw an error for any string different that a valid GUID

const testGuid: GUID = 'e1b53ee5-4e77-4885-9fb1-e54921d9d87f';  // valid

const testGuid: GUID = 'abcdd-efggh-ijkgl-mndop-qrstuvwx1234';  // For some reason doesn't throw an error
0

There are 0 best solutions below