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

如何创建值类型依赖于键的TypeScript映射类型?

实现指定键类型为number、其他键为boolean的映射类型

可以实现这个需求,核心思路是将指定键集合的类型与剩余字符串键的类型做合理合并,避免索引签名冲突。

正确实现方式

type MyMappedType<K extends string> = Record<K, number> & Omit<{ [key: string]: boolean }, K>;

为什么之前的写法会报错?

  • 直接用[P in string]: P extends K ? number : boolean:当P是string类型时,TypeScript无法确定它是否属于K(因为string是所有字符串的超集),条件判断会统一返回boolean,导致所有键值都被限制为布尔类型。
  • 直接交叉Record<K, number> & { [key: string]: boolean }:两个索引签名会冲突,TypeScript会要求值类型为number & boolean(即never),自然无法通过类型检查。
  • 使用Exclude<string, K>:string是无限的字符串集合,Exclude<string, K>无法从无限集中排除有限的联合类型,TypeScript会将其简化为string,等于没做排除。

验证示例

const foo: MyMappedType<'foo' | 'bar'> = {
  foo: 42, // 符合number类型要求
  bar: 43, // 符合number类型要求
  qux: true, // 符合boolean类型要求
  quux: false // 符合boolean类型要求
};

// 错误示例:指定键赋值布尔值会报错
const badFoo: MyMappedType<'foo' | 'bar'> = {
  foo: true, // Type 'boolean' is not assignable to type 'number'
  bar: 43,
  qux: true
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:44:58