This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for TypeScript puzzle on BFE.dev
24. implement LengthOfString<T>
Solution:
type LengthOfString<T extends string> = T['length'];type A = LengthOfString<'BFE.dev'> // 7type B = LengthOfString<''> // 0
Explanation:
In this solution, we define a generic type T
that extends the string
type, and then use the built-in length
property of the string
type to get the length of the string. We do this by using an index type query with T['length']
, which fetches the length
property of the T
type.
Then we use this LengthOfString<T>
type to get the length of the given string. For example, the LengthOfString<'BFE.dev'>
would return 7
and LengthOfString<''>
would return 0
.