在TypeScript中使用泛型将字符串数组转换为不同类型与值
用泛型批量生成数组对应的类型和映射对象
定义通用泛型类型
先封装两个通用泛型类型,替代针对单个数组的重复定义:
// 提取只读字符串数组的元素联合类型 type ElementType<T extends readonly string[]> = T[number]; // 生成键值与元素相同的映射类型 type TypeMap<T extends readonly string[]> = { [K in ElementType<T>]: K };
封装通用映射生成函数
写一个泛型函数,统一处理数组到映射对象的转换逻辑:
function createValueMap<T extends readonly string[]>(arr: T): TypeMap<T> { return arr.reduce((obj, key) => { obj[key] = key; return obj; }, {} as TypeMap<T>); }
批量使用示例
针对任意类似的只读字符串数组,直接复用上述类型和函数即可:
// 水果数组示例 const fruitsArray = ["apple", "banana", "peach"] as const; type FruitsType = ElementType<typeof fruitsArray>; // "apple" | "banana" | "peach" type FruitsTypeMap = TypeMap<typeof fruitsArray>; // { apple: "apple", banana: "banana", peach: "peach" } const fruitsMap = createValueMap(fruitsArray); // 自动推导为FruitsTypeMap类型 // 蔬菜数组示例 const vegetablesArray = ["carrot", "spinach", "broccoli"] as const; type VegetablesType = ElementType<typeof vegetablesArray>; type VegetablesTypeMap = TypeMap<typeof vegetablesArray>; const vegetablesMap = createValueMap(vegetablesArray);
说明
- 泛型约束
T extends readonly string[]确保传入的是通过as const声明的只读字符串数组,保证类型推断的准确性 - 函数内部的
{} as TypeMap<T>用于给reduce初始值指定正确类型,避免类型报错 - 所有类型和对象都能自动推导,无需针对每个数组重复写reduce和类型定义
内容的提问来源于stack exchange,提问作者vd1
相关产品推荐
相关产品推荐

