Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Last active June 13, 2021 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/36e04368fd64dbd540cb8650f256f37f to your computer and use it in GitHub Desktop.
Save Oaphi/36e04368fd64dbd540cb8650f256f37f to your computer and use it in GitHub Desktop.
Types for checking if phone is in E164 format
type Digit = "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "0";
type EveryOfType<A extends readonly any[], T> = keyof {
[P in Exclude<keyof A, keyof any[]> as A[P] extends T ? never : P]: P;
} extends never
? true
: false;
type SplitString<
T extends string,
A extends string[] = []
> = T extends `${infer F}${infer L}` ? SplitString<L, [...A, F]> : A;
type E164Format<T extends string> = SplitString<T> extends [
"+",
Digit,
Digit,
Digit,
...infer L
]
? L["length"] extends 12
? EveryOfType<L, Digit> extends true
? T
: never
: never
: never;
type testOK = E164Format<"+191012345678910">; //"+191012345678910"
type testLen = E164Format<"+19101234567891">; //never, 11 digits after
type testType = E164Format<"+1910123456B8910">; //never, "B" encountered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment