以下为ChatGPT自动生成的解答,正确与否请自行判断。
BFE.devAI解答 - TypeScript 类型谜题
51. implement Capitalize<T>
type MyCapitalize<T extends string> = T extends `${infer First}${infer Rest}`
? `${Uppercase<First>}${Rest}`
: never;
Explanation:
- We define a generic type
T
which extendsstring
. - We use a conditional type to check if
T
can be split into two parts - the first character and the rest of the string. - If it can, we use the
Uppercase
built-in type to uppercase the first character, and concatenate it with the rest of the string using string literal types. - If
T
cannot be split into two parts, we returnnever
type which represents a type that should never be used.