#298Medium

Length of String

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.

Challenge Instructions: Length of String

Medium

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).

ChallengeSolution
// 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>>,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Video Walkthrough

Detailed Explanation

type LengthOfString<
  S extends string,
  Count extends string[] = [],
> = S extends `${infer First}${infer Rest}`
  ? LengthOfString<Rest, [...Count, First]>
  : Count['length']

How it works:

This 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.

Share this challenge

Learn the Concepts