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

TypeScript:如何用选项数组作为另一个Prop的类型?

用TypeScript实现通过options约束selected的Prop类型

你需要的需求完全可行,核心是利用泛型关联options和selected的类型,让TypeScript自动推导并约束两者的关系。

原代码问题

你的原代码中selected只是宽泛的string类型,无法和options的具体值关联,所以不会触发类型错误:

// Props
export interface Props {
  options: string[];
  selected: string; // 未与options的值关联
}

// Component
const Component = ({ options, selected }: Props) => {
  return <div>{selected}</div>;
};

// Usage of component somewhere else
<Component
  options={['2020', '2021', '2022', '2023']}
  selected="1999" // <--- 这里不会触发类型错误
/>

解决方案:泛型关联类型

修改为泛型组件,让selected的类型严格依赖options的元素类型:

// 泛型Props接口,T代表options中元素的类型
export interface Props<T extends string> {
  options: T[];
  selected: T;
}

// 组件使用泛型T,让TypeScript自动推导类型
const Component = <T extends string>({ options, selected }: Props<T>) => {
  return <div>{selected}</div>;
};

// 使用示例
// 错误用法:selected不在options中,TypeScript会报错
<Component
  options={['2020', '2021', '2022', '2023']}
  selected="1999" // ❌ 类型错误:"1999"不能赋值给"2020" | "2021" | "2022" | "2023"
/>

// 正确用法:selected属于options中的值
<Component
  options={['2020', '2021', '2022', '2023']}
  selected="2021" // ✅ 类型合法
/>

原理说明

  • 泛型T会自动捕获options数组的字面量联合类型(比如'2020' | '2021' | '2022' | '2023')
  • selected被约束为T类型,因此必须是options数组中的某一个值
  • 这种方式不需要提前定义固定的选项类型,完全适配任意字符串数组的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:15:32