Last active
June 13, 2021 15:06
-
-
Save Oaphi/36e04368fd64dbd540cb8650f256f37f to your computer and use it in GitHub Desktop.
Types for checking if phone is in E164 format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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