You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将数组字面量值转为对象键并解决TypeScript类型问题

解决TypeScript中readonly数组转明确键对象的问题

要解决readonly数组传入函数的类型兼容问题,同时让TypeScript推导出包含数组具体元素作为键的精确对象类型,只需调整函数的泛型约束和返回类型即可:

修改后的函数实现

function toBoolMap<A extends readonly string[]>(array: A): { [K in A[number]]: true } {
    return Object.assign({}, ...array.map(key => ({[key]: true}))) as { [K in A[number]]: true };
}

关键调整说明

  • 泛型约束修改:将原约束A extends Array<string>改为A extends readonly string[],让函数既能接受普通可变数组,也能兼容as const生成的readonly数组,解决"readonly无法赋值给可变类型"的错误。
  • 精确返回类型:使用映射类型{ [K in A[number]]: true },TypeScript会自动提取数组的字面量元素类型作为对象键,生成你期望的明确类型(和示例中的type x完全一致)。
  • 类型断言:由于Object.assign的返回类型无法自动匹配精确的映射类型,添加安全的类型断言确保类型推导正确。

使用示例

const osFiles = [
    "$RECYCLE.BIN",
    "DumpStack.log.tmp",
    "System Volume Information"
] as const;

// 推导后的类型:{ "$RECYCLE.BIN": true; "DumpStack.log.tmp": true; "System Volume Information": true; }
const osFileMap = toBoolMap(osFiles);

// 可直接通过键快速查找,且TypeScript会提供类型提示
console.log(osFileMap["$RECYCLE.BIN"]); // true

内容的提问来源于stack exchange,提问作者Shape

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:27:11