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

TypeScript如何限制对象仅包含Options中的单个键值对?

如何定义仅包含单个指定键的TypeScript对象类型?

问题场景

初始代码尝试用字符串字面量联合类型作为对象键的约束,但触发ts(1337)错误:

type Options = 'option1' | 'option2' | 'option3'

type ComplexValue = { [key: Options]: string } // ts(1337)错误

需求是:ComplexValue类型的对象只能包含Options中的某一个键,且是单个键值对。

尝试用映射类型或Record修正后:

type ComplexValue = { [K in Options]: string }

// 或等价的Record写法
type ComplexValue = Record<Options, string>

赋值单个键的对象时会触发缺失属性错误:

Type '{ [x: string]: string; }' is missing the following properties from type 'ComplexValue': option2, option3.ts(2740)

若给键添加可选符号?:

type ComplexValue = { [key in Options]?: string }

会允许对象包含多个键或零个键,不符合“仅单个键”的需求。


解决方案

可以通过分布式联合类型实现严格的单个键约束,以下是两种写法:

写法一:显式约束其他键为never类型

type Options = 'option1' | 'option2' | 'option3'

// 生成仅包含指定单个键的类型
type SingleKeyObject<K extends string> = {
  [P in K]: string
} & {
  // 其他Options中的键只能是never类型(即无法存在或赋值)
  [key in Exclude<Options, K>]?: never
}

type ComplexValue = SingleKeyObject<Options>

写法二:简洁的索引访问类型实现

type Options = 'option1' | 'option2' | 'option3'

// 遍历Options生成每个单键类型,再合并为联合类型
type ComplexValue = {
  [K in Options]: { [P in K]: string }
}[Options]

验证效果

// ✅ 合法:仅包含单个Options中的键
const valid1: ComplexValue = { option1: 'ziv' }
const valid2: ComplexValue = { option2: 'test' }

// ❌ 非法:包含多个键
const invalid1: ComplexValue = { option1: 'ziv', option2: 'test' }

// ❌ 非法:包含不在Options中的键
const invalid2: ComplexValue = { option4: 'error' }

// ❌ 非法:没有任何键
const invalid3: ComplexValue = {}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:45:27