🤔 ️ requirements
Implement a generic Underscore that returns a hump Underscore type G for a given Underscore string type T
type camelCase1 = Underscore<'hello_world_with_types'> // expected to be 'helloWorldWithTypes'
Copy the code
📖 knowledge
- TS built-in types
Convert string literal type to uppercase
type Uppercase<S extends string> = intrinsic; Intrinsic TS built-in
Convert string literal type to lowercase
type Lowercase<S extends string> = intrinsic;
Convert first character of string literal type to uppercase
type Capitalize<S extends string> = intrinsic;
Convert first character of string literal type to lowercase
type Uncapitalize<S extends string> = intrinsic;
Copy the code
- What happens when you have unions in substitution positions? It produces the set of every possible string literal that could be represented by each union member.
🔗 Knowledge link
- Template strings
😢 questions & Answers
- Underline to hump
- answer
🍗 scenario
type Underscore<S extends string> = S extends ' ' ? ' ' : (S extends `${infer L}_${infer R}` ? `${L}${Underscore<Capitalize<R>>}` : S)
// This function converts the hump to an underscore
function toHump(name: string) {
return name.replace(/\_(\w)/g.function(_, letter){
return letter.toUpperCase();
});
}
function underscore<T extends string> (o: Record<T, any> ) :Record<Underscore<T>, any>
function underscore(o: Record<string.any>){
const result: Record<string.any> = {};
Object.entries(o).forEach(([key, value]) = > {
result[toHump(key)] = value;
})
return result;
}
const res = underscore({ 'user_name': 'name'})
console.log(res) // { 'userName' : 'name' }```
Copy the code