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).
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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount