Compute the length of a string literal, which behaves like `String.length`. Master TypeScript template literal types in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll compute the length of a string literal, which behaves like String.length.
Compute the length of a string literal, which behaves like String#length.
Change the following code to make the test cases pass (no type check errors).
// Video Solution: https://youtube.com/watch?v=7eNIb_jZRJU
/* _____________ Your Code Here _____________ */
type LengthOfString<S extends string> = any
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'
type cases = [
Expect<Equal<LengthOfString<''>, 0>>,
Expect<Equal<LengthOfString<'kumiko'>, 6>>,
Expect<Equal<LengthOfString<'reina'>, 5>>,
Expect<Equal<LengthOfString<'Sound! Euphonium'>, 16>>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
type LengthOfString<
S extends string,
Count extends string[] = [],
> = S extends `${infer First}${infer Rest}`
? LengthOfString<Rest, [...Count, First]>
: Count['length']How it works:
S to be a string with extends stringS extends ${infer First}${infer Rest} matches the string type and captures the first letter into First and the rest of the string into Rest? LengthOfString<Rest, [...Count, First]> recursively calls LengthOfString with the rest of the string and the first letter: Count['length'] returns the length of the stringThis challenge helps you understand TypeScript's template literal types and how to apply this concept in real-world scenarios.
This challenge is originally from here.