以下为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
Twhich extendsstring. - We use a conditional type to check if
Tcan be split into two parts - the first character and the rest of the string. - If it can, we use the
Uppercasebuilt-in type to uppercase the first character, and concatenate it with the rest of the string using string literal types. - If
Tcannot be split into two parts, we returnnevertype which represents a type that should never be used.