javascripttypescripttypes

Define a TypeScript type that takes a lowercase word


Is there any way to define that kind of type in TypeScript? Something like:

type lowercaseWord = /[a-z]/

But that defines a string instead? (I think the code above will define a regex.)


Solution

  • Yes and no. There is built int (intrinsic) type LowerCase but it works as an utility type. It works as String.prototype.toLowerCase and not as a regex. See example:

    type Result = Lowercase<'A'> // 'a'
    

    Playground

    Here you can find more types: Capitalize, Uncapitalize, Lowercase, Uppercase

    If you want to apply such restriction it is possible to do in the function:

    type UpLetters = 'A' | 'B' | 'C' // provide all allowed letters
    type LowLetters = Lowercase<UpLetters>
    
    type Letters = UpLetters | LowLetters
    
    type IsAllowed<T extends string> = T extends Letters ? T extends Lowercase<T> ? T : never : never
    
    const lower = <T extends string>(str: IsAllowed<T>) => null
    
    /**
     * Ok
     */
    lower('a') // ok
    
    /**
     * Error
     */
    lower('A') // error
    lower('1') // error
    lower('$%^') // error
    

    Please keep in mind that

    const x: Lowercase<string> = 'A' // no error
    

    will not trigger an error