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

Typescript如何实现关联的对象key与对应value参数的类型约束

实现步骤

  1. 首先给food对象添加as const断言,让TS能将数组元素推导为具体的字面量类型,而不是通用的string[]
const food = {
  fruit: ['apples', 'oranges'],
  meat: ['chicken', 'pig']
} as const;
  1. 给makeFood函数添加泛型约束,将category和ingredient的类型做绑定:
// 泛型T绑定当前传入的category类型
function makeFood<T extends keyof typeof food>(
  ingredient: typeof food[T][number], // ingredient自动匹配当前category对应的数组成员
  category: T
) {
 switch(true) {
   case category === 'fruit' && ingredient === 'apples':
    // 此时TS会自动推导ingredient类型为 'apples'|'oranges'
    break
   case category === 'fruit' && ingredient === 'oranges':
    // do something
    break
   case category === 'meat' && ingredient === 'chicken':
    // do something
    break
   case category === 'meat' && ingredient === 'pig':
    // do something
    break
 }
}

效果说明

  • 调用函数时如果传入category: 'fruit',TS会自动提示ingredient只能填apples/oranges
  • 传入不匹配的参数会直接报错,例如makeFood('chicken', 'fruit')会触发类型错误
  • 所有类型都从food对象自动推导,后续修改food的结构不需要手动调整函数类型,维护成本更低

如果需要复用类型,可以单独抽离定义:

type FoodCategory = keyof typeof food;
type FoodIngredient<T extends FoodCategory> = typeof food[T][number];

function makeFood<T extends FoodCategory>(ingredient: FoodIngredient<T>, category: T) {
  // 函数逻辑不变
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:45:04