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

如何在TypeScript中限制keyof T仅接受值为特定类型的键?

如何限制keyof T仅接受对应值为特定类型的键?

当然可以啦!TypeScript的条件类型和映射类型组合起来,就能精准筛选出那些值类型为FancyType的键,完美解决你的需求。

第一步:定义一个通用工具类型

我们先写一个可复用的工具类型,专门用来提取对象中值类型符合指定条件的键:

type KeysOfType<T, TargetType> = {
  // 遍历目标对象的所有键
  [Key in keyof T]: 
    // 如果当前键对应的值是TargetType的子类型,保留该键;否则标记为never
    T[Key] extends TargetType ? Key : never
// 最后取出所有非never的键(never类型会被自动排除)
}[keyof T];

第二步:应用到你的函数上

回到你的代码,把someFunction的参数类型替换成这个工具类型即可:

// 先假设FancyType已经定义完成
interface FancyType { /* 这里是FancyType的具体定义 */ }

interface Something { 
  id: number; 
  name: string; 
  value1: FancyType; 
  value2: FancyType; 
  value3: FancyType; 
}

// 复用刚才的工具类型
type KeysOfType<T, TargetType> = { [Key in keyof T]: T[Key] extends TargetType ? Key : never }[keyof T];

function someFunction(key: KeysOfType<Something, FancyType>) { 
  // 现在key只能是value1 | value2 | value3,传入id或name会直接触发TypeScript报错
  console.log(`操作FancyType类型的属性:${key}`);
}

测试效果

  • 合法调用:someFunction('value1') → 完全符合类型要求
  • 非法调用:someFunction('id') → TypeScript会立即提示类型错误,因为id对应的值是number,不符合FancyType的类型约束

如果需要精确匹配类型(排除FancyType的子类型),可以稍微调整工具类型:

type KeysOfExactType<T, TargetType> = {
  [Key in keyof T]: 
    T[Key] extends TargetType ? 
      (TargetType extends T[Key] ? Key : never) 
    : never
}[keyof T];

这种情况下,只有当键对应的值类型和TargetType完全一致时才会被选中,子类型不会被包含进来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:06:40