Typescript 类型体操 —— Underscore

1,319 阅读1分钟

🤔️要求

实现一个范型 Underscore,对于给定的下划线形式的字符串类型 T, 返回驼峰形式的类型G

type camelCase1 = Underscore<'hello_world_with_types'> // expected to be 'helloWorldWithTypes' 

📖知识点

  1. TS 内置类型
   Convert string literal type to uppercase
   type Uppercase<S extends string> = intrinsic; // intrinsic TS内置的
   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;
  1. 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.

🔗知识链接

  1. 知识点:模板字符串

😢问题 & 解答

  1. 下划线转驼峰
  2. 解答

🍗场景

type Underscore<S extends string> = S extends '' ? '' : (S extends `${infer L}_${infer R}` ? `${L}${Underscore<Capitalize<R>>}` : S)
// 该函数将驼峰转化为下划线
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' }```