Go Back

Refer: Medium - Length of String

Describe

Compute the length of a string literal, which behaves like String#length.

Test Cases

code snippetCopytypescript
import { Equal, Expect } from '@type-challenges/utils' type cases = [ Expect<Equal<LengthOfString<''>, 0>>, Expect<Equal<LengthOfString<'kumiko'>, 6>>, Expect<Equal<LengthOfString<'reina'>, 5>>, Expect<Equal<LengthOfString<'Sound! Euphonium'>, 16>>, ]

Solution

code snippetCopytypescript
type LengthOfString<S extends string, C extends any[] = []> = S extends `${infer P}${infer K}` ? LengthOfString<K, [...C, P]> : C['length']