Alphabet-only string in typescript (without recursion)

1 day ago 3
ARTICLE AD BOX

Similar question: Is it possible to annotate alphabet-only string in typescript?

The goal is to create a non-recursive type which will able to detect if the passed string contains only alphabet characters (TS version is 5.9.3)

First attempt (straight):

type Special = Lowercase<string> & Uppercase<string>; type IsAlphabet<T extends string> = T extends `${string}${Special}${string}` ? never : T; type Testing = IsAlphabet<"1">; // 1

I thought that the reason is that Special contains empty string so it just checks 3 times empty string and fails because "1" doesn't extends ""

Second attempt (exclude empty string):

type SpecialChar = Lowercase<string> & Uppercase<string>; type Special = `${SpecialChar}${string}`; const a: Special = ''; // Type 'string' is not assignable to type '`${SpecialChar}${string}`' const b: Special = 'a'; // Type 'string' is not assignable to type '`${SpecialChar}${string}`' const c: Special = '1'; // OK type IsAlphabet<T extends string> = T extends `${string}${Special}${string}` ? never : T; type Testing = IsAlphabet<"1">; // 1

I don't know why but Exclude<Lowercase<string> & Uppercase<string>, ''> doesn't exclude the empty string

Third attempt (step by step):

type SpecialChar = Lowercase<string> & Uppercase<string>; type Special = `${SpecialChar}${string}`; const a: Special = ''; // Type 'string' is not assignable to type '`${SpecialChar}${string}`' const b: Special = 'a'; // Type 'string' is not assignable to type '`${SpecialChar}${string}`' const c: Special = '1'; // OK type IsAlphabet<T extends string> = T extends Special ? never : ( T extends`${string}${Special}` ? never : ( T extends`${Special}${string}` ? never : ( T extends`${string}${Special}${string}` ? never : T ) ) ); type Testing1 = IsAlphabet<"1">; // never type Testing2 = IsAlphabet<"1a">; // never type Testing3 = IsAlphabet<"a1">; // never type Testing4 = IsAlphabet<"a1a">; // never type Testing5 = IsAlphabet<"aa1aa">; // "aa1aa" type Testing6 = IsAlphabet<"HelloWorld">; // "HelloWorld" Why none of them work? (It seems like string matches only 1 character not the any string) Is there any way to not use the recursion?
Read Entire Article