この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - TypeScript タイプパズル
51. implement Capitalize<T>
type MyCapitalize<T extends string> = T extends `${infer First}${infer Rest}` ? `${Uppercase<First>}${Rest}` : T;
Explanation:
- We define a generic type
MyCapitalize<T>
that takes a string typeT
as input. - Using conditional types, we check if
T
is of the form${infer First}${infer Rest}
. If it is, then we know thatFirst
is the first character of the string andRest
is the rest of the string. - We use the
Uppercase<T>
built-in utility to convertFirst
to uppercase and then concatenate it withRest
to form the final capitalized string. - If
T
is not of the required form (i.e., it is an empty string, a single character string, or not a string at all), then we returnT
as is.