type-challenges-solutions icon indicating copy to clipboard operation
type-challenges-solutions copied to clipboard

type-challenges-solutions/en/medium-length-of-string

Open utterances-bot opened this issue 2 years ago • 1 comments

Length of String

This project is aimed at helping you better understand how the type system works, writing your own utilities, or just having fun with the challenges.

https://ghaiklor.github.io/type-challenges-solutions/en/medium-length-of-string.html

utterances-bot avatar Nov 12 '22 18:11 utterances-bot

Share my version with the idea that:

  1. convert string to tuple first (since we can get length from tuple)
  2. get the length of the tuple
type StringToTuple<S extends string> = S extends `${S[0]}${infer Rest}` ? [S, ...StringToTuple<Rest>] : []
type LengthOfString<S extends string> = StringToTuple<S>['length'];

Something to emphasize is, I use ${S[0]}${infer Rest} instead of ${infer Head}${infer Rest} since I think it would be more definite which does not depend on the ts implementation.

zhaoyao91 avatar Nov 12 '22 18:11 zhaoyao91