问题 #
Implement Capitalize<T>
which converts the first letter of a string to uppercase and leave the rest as-is.
For example
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
拆分 #
S
只能为字符串- 使用
infer L
和infer R
获取不同位置的字符串 - 使用
Uppercase<L>
来获取首字母大写的字符串 - 如果不允许使用
Uppercase
则可以写一个字符串映射的类型来获取大写