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

如何创建仅含字符串联合类型中单个键的对象类型?

TypeScript 创建仅含单个指定键的对象类型

你可以通过联合类型 + 映射类型实现这种仅包含单个指定键的对象类型,具体实现如下:

基础实现

先定义你的键联合类型,再生成对应的单键对象联合类型:

type Key = "a" | "b" | "c";

// 生成每个键对应的单键对象类型,合并为联合类型
type SingleKeyObject<K extends string> = {
  [P in K]: { [Q in P]: any };
}[K];

// 合法示例
const result: SingleKeyObject<Key> = { a: "hello there" };
const result2: SingleKeyObject<Key> = { b: "General Kenobi" };
const result3: SingleKeyObject<Key> = { c: 2137 };

// 非法示例(会触发TypeScript报错)
const wrongType: SingleKeyObject<Key> = { a: "hello there", b: "General Kenobi" }; // 包含多个键
const wrongType2: SingleKeyObject<Key> = {}; // 无任何键

原理说明

SingleKeyObject 类型的逻辑:

  1. 通过映射类型 [P in K] 遍历联合类型中的每个键,为每个键生成一个仅包含该键的对象类型(比如{a: any}、{b: any})
  2. 通过索引访问 [K] 将这些单键对象类型合并成一个联合类型
  3. TypeScript会强制对象必须匹配联合类型中的某一项,自然就限制了只能有一个指定的键

自定义值类型

如果需要限制对象值的类型,可以给泛型添加第二个参数:

type Key = "a" | "b" | "c";

type SingleKeyObject<K extends string, V = any> = {
  [P in K]: { [Q in P]: V };
}[K];

// 指定值为字符串类型
const resultStr: SingleKeyObject<Key, string> = { a: "hello there" };
// 指定值为数字类型
const resultNum: SingleKeyObject<Key, number> = { c: 2137 };

// 值类型不匹配会报错
const wrongValue: SingleKeyObject<Key, string> = { c: 2137 };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:23:42