Determine if the given letter is an alphabet. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement an IsAlphabet<S> type that determines whether a given single-character string type is an alphabetic letter (a-z or A-Z).
Determine if the given letter is an alphabet.
Change the following code to make the test cases pass (no type check errors).
type cases = [
Expect<Equal<IsAlphabet<'A'>, true>>,
Expect<Equal<IsAlphabet<'z'>, true>>,
Expect<Equal<IsAlphabet<'9'>, false>>,
Expect<Equal<IsAlphabet<'!'>, false>>,
Expect<Equal<IsAlphabet<'😂'>, false>>,
Expect<Equal<IsAlphabet<''>, false>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type IsAlphabet<S extends string> =
Uppercase<S> extends Lowercase<S>
? false
: Lowercase<S> extends Uppercase<S>
? false
: true;How it works:
Uppercase and Lowercase produce different results (e.g., Uppercase<'a'> is 'A' and Lowercase<'a'> is 'a'). This means Uppercase<S> extends Lowercase<S> will be false for letters.Uppercase and Lowercase return the same string, so Uppercase<S> extends Lowercase<S> will be true, and we return false.'' also passes through Uppercase and Lowercase unchanged, so it correctly returns false.An alternative approach explicitly lists all 26 letters:
type Alphabet = 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'h' | 'i' | 'j' | 'k' | 'l' | 'm' | 'n' | 'o' | 'p' | 'q' | 'r' | 's' | 't' | 'u' | 'v' | 'w' | 'x' | 'y' | 'z';
type IsAlphabet<S extends string> = Lowercase<S> extends Alphabet ? true : false;This challenge helps you understand TypeScript's built-in string manipulation types (Uppercase and Lowercase) and how to apply them for character classification in real-world scenarios.
This challenge is originally from here.