实现 Capitalize<T>,它将字符串的第一个字母转换为大写,其余字母保持原样
例如:
type capitalized = Capitalize<'hello world'> // expected to be 'Hello world'
type MyCapitalize<S extends string> = S extends `${infer L}${infer R}` ? `${Uppercase<L>}${R}` : S
关于 TS 如何确定 L 和 R 中的哪一个应该占据其余字符?例如,如果 S 是 'abc' ,为什么是 L='a' 和 R='bc',而不是 L='ab' 和 R='c'?
经过测试,我认为它是这样工作的:
| TypeScript | Regex |
|---|---|
${infer A} |
/(.*)/ |
${infer A}${infer B} |
/(.+?)(.*)/ |
${infer A}${infer B}${infer C} |
/(.+?)(.+?)(.*)/ |