この解答例は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 typeTas input. - Using conditional types, we check if
Tis of the form${infer First}${infer Rest}. If it is, then we know thatFirstis the first character of the string andRestis the rest of the string. - We use the
Uppercase<T>built-in utility to convertFirstto uppercase and then concatenate it withRestto form the final capitalized string. - If
Tis not of the required form (i.e., it is an empty string, a single character string, or not a string at all), then we returnTas is.