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
51. implement Capitalize<T>
One possible solution could be:
type MyCapitalize<S extends string> = S extends `${infer F}${infer R}` ? `${Uppercase<F>}${R}` : S;
In this solution, we are using a conditional type with template literal types to split the input string into its first character (infer F
) and the rest of the string (infer R
). We then use the Uppercase
utility type to transform F
to uppercase and concatenate it with R
to get the capitalized string. If S
is empty or not a string, we just return it as is.
We can test the solution:
type A = MyCapitalize<'bfe'> // 'Bfe'type B = MyCapitalize<'Hello, world!'> // 'Hello, world!'type C = MyCapitalize<1234> // 1234