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

如何在TypeScript中限制React state仅为指定对象数组的value可选值

实现方案

  1. 首先给studyTypes数组添加as const断言,固定数组内部属性的字面量类型,避免TypeScript将value的类型自动拓宽为string:
const studyTypes = [
   {
     value: "ENG",
     label: "ENG-RU",
   },
   {
     value: "RU",
     label: "RU-ENG",
   },
] as const;
  1. 从studyTypes中提取所有value值组成的联合类型,可以定义为类型别名方便复用:
type StudyType = typeof studyTypes[number]['value'];
// 此时 StudyType 的实际类型等价于 "ENG" | "RU"
  1. 将React useState的泛型参数从string替换为上面定义的StudyType即可:
const [typeStudy, setTypeStudy] = React.useState<StudyType>("ENG");

补充说明

后续如果在studyTypes数组中新增其他带有value属性的对象,StudyType会自动同步新增对应的字面量类型,无需手动修改类型定义,能保证运行时可选值和类型约束完全同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 02:57:00