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

TypeScript中如何约束映射类型仅接受字符串类型键?

解决TypeScript映射类型中键类型约束问题

问题原因

TypeScript里keyof操作符返回的类型是string | number | symbol(对象键的合法类型集合),而你定义的Key<K>要求泛型参数K必须是string类型,直接将keyof Type传入Key会因为类型范围不匹配触发报错。

核心解决方案

给泛型Type添加约束,限定它的键只能是string类型,这样keyof Type就会被缩小为string类型,刚好满足Key<K>的约束要求:

// 原Key类型定义
type Key<K extends string> = {
    key: K
};

// 添加键类型约束后的映射类型
type OptionsFlags<Type extends Record<string, any>> = {
  [K in keyof Type]: Key<K>;
};

验证示例

用仅含字符串键的对象测试:

type User = {
  name: string;
  age: number;
};

// 正确生成目标类型,每个属性值都是对应键的Key类型
type UserOptions = OptionsFlags<User>;
// 等价于:
// type UserOptions = {
//   name: Key<"name">;
//   age: Key<"age">;
// };

扩展场景处理

如果需要兼容含数字、symbol键的对象,但只保留字符串键对应的属性,可以通过类型过滤实现:

type OptionsFlags<Type> = {
  [K in keyof Type as K extends string ? K : never]: Key<K>;
};

这种写法会自动忽略Type中键为number或symbol的属性,只处理字符串键的部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:09:52