Skip to content

Instantly share code, notes, and snippets.

@PhoneDroid
Created September 26, 2023 03:22
Show Gist options
  • Select an option

  • Save PhoneDroid/f43292bbc848289c3c3e81f541fdda4e to your computer and use it in GitHub Desktop.

Select an option

Save PhoneDroid/f43292bbc848289c3c3e81f541fdda4e to your computer and use it in GitHub Desktop.

Curtesy to vyenkv answer.

type LengthOf <
    String extends string ,
    Sum extends 0 [] = []
> = String extends `${ string }${ infer $Rest }`
    ? LengthOf< $Rest , [ ... Sum , 0 ] >
    : Sum[ 'length' ]


type HasLength <
    String extends string , 
    Length extends number
> = LengthOf<String> extends Length 
    ? true 
    : false

type False = HasLength<'Hello',4> 
type True = HasLength<'World',5>
type LengthOf <                                     //
    String extends string ,                         //
    Sum extends 0 [] = []                           // Tuple of zeros
> = String extends `${ string }${ infer $Rest }`    // Destructures string into it's first char + remainder
    ? LengthOf< $Rest , [ ... Sum , 0 ] >           // Counts the length of the remainder + adds zero to tuple
    : Sum[ 'length' ]                               // If the end is reached, returns length of tuple
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment