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

如何基于对象中字符串数组的值定义TypeScript联合类型?

如何从对象的字符串数组值中推导TypeScript联合类型?

假设我们有这样一个包含字符串数组的对象:

const STUFF = {
  abc: ["string_1", "string_2"],
  def: ["string_3", "string_4"],
  xyz: ["string_1", "string_2", "string_4"],
}

要定义一个仅包含该对象所有数组元素值的联合类型(即"string_1" | "string_2" | "string_3" | "string_4"),可以按以下步骤操作:

  1. 给原对象添加as const断言,让TypeScript锁定数组元素的字面量类型,避免自动推断为宽泛的string[]:
const STUFF = {
  abc: ["string_1", "string_2"],
  def: ["string_3", "string_4"],
  xyz: ["string_1", "string_2", "string_4"],
} as const;
  1. 通过TypeScript的类型操作符提取联合类型:
type StuffStr = typeof STUFF[keyof typeof STUFF][number];

类型推导逻辑说明:

  • typeof STUFF:获取对象STUFF的类型结构
  • keyof typeof STUFF:得到对象所有键的联合类型,即"abc" | "def" | "xyz"
  • typeof STUFF[keyof typeof STUFF]:获取对象所有属性值的类型,也就是各个只读数组的字面量类型联合
  • [number]:从数组类型中提取所有元素的类型,最终得到目标的字符串字面量联合类型

验证一下效果:

const validVal: StuffStr = "string_2"; // 类型合法
const invalidVal: StuffStr = "string_5"; // 类型报错,不符合允许的取值范围

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:32:30