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

TypeScript如何从Symbol键元组构造匹配预设类型的映射对象类型

解决方案

核心思路是通过T[number]提取元组内所有元素的联合类型,再遍历该联合类型作为对象键,匹配Attributes中对应的值类型即可。

完整实现代码

const A = Symbol.for(":a")
const B = Symbol.for(":b")
const C = Symbol.for(":c")

interface Attributes {
  [A]: string
  [B]: number
  [C]: boolean
}

type AttributeKeys = ReadonlyArray<keyof Attributes>

declare function pattern<Pattern extends AttributeKeys>(...attrs: Pattern): Pattern
const PATTERN = pattern(A, B) // 推断类型为 [typeof A, typeof B]

// 方案1:手写映射类型
declare function pull<T extends AttributeKeys>(pattern: T): { [K in T[number]]: Attributes[K] }
// 方案2:直接使用TS内置Pick工具类,效果完全一致
// declare function pull<T extends AttributeKeys>(pattern: T): Pick<Attributes, T[number]>

const entity = pull(PATTERN)
// 自动推断类型为 { [A]: string, [B]: number },符合预期

原写法错误原因

  • pull1遍历的是元组的索引(keyof T拿到的是0/1/length这类数组自有属性),而非元组存储的Symbol键,永远无法匹配Attributes的键,所以返回never。
  • pull2的类型判断逻辑错误,K extends T是判断键是否属于元组类型本身,而非元组包含的元素,改为K extends T[number]即可正常匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:36:05