type-challenges-solutions
type-challenges-solutions copied to clipboard
type-challenges-solutions/en/medium-length-of-string
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
Share my version with the idea that:
- convert string to tuple first (since we can get length from tuple)
- 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.