Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active October 25, 2023 21:41
Show Gist options
  • Save tobiashm/3ef6648c67c189e508b36aff750e5382 to your computer and use it in GitHub Desktop.
Save tobiashm/3ef6648c67c189e508b36aff750e5382 to your computer and use it in GitHub Desktop.
TypeScript check for CVR-nr
type LengthOfString<T extends string, S extends string[] = []> = T extends `${string}${infer R}` ? LengthOfString<R, [...S, string]> : S['length'];
type HasLengthOfEight<T extends string> = LengthOfString<T> extends 8 ? T : never;
type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type IsNumeric<T extends string, S = T> = T extends Digit ? S : T extends `${Digit}${infer R}` ? IsNumeric<R, S> : never;
type StartsWithNonZeroDigit<T extends string> = T extends `${Exclude<Digit, '0'>}${string}` ? T : never;
type CVRNummer<T extends string> = IsNumeric<T> & HasLengthOfEight<T> & StartsWithNonZeroDigit<T>;
const cvr = <T extends string>(input: CVRNummer<T>) => input;
cvr('12345678');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment