[Typescript] 31. Medium - Length of String

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

/* _____________ Your Code Here _____________ */

type LengthOfString<S extends string, ACC extends any[] = []> = S extends '' ? ACC['length']: S extends `${infer First}${infer RT}` ? LengthOfString<RT, [...ACC, First]> : never;


/* _____________ Test Cases _____________ */
import type { 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>>,
]

 

posted @ 2022-09-14 15:20  Zhentiw  阅读(19)  评论(0)    收藏  举报