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

TypeScript如何根据elType属性动态限定elementConfig的允许属性

实现方案

使用TypeScript的**判别联合类型(Discriminated Union)**即可实现需求:将elType作为判别属性,为不同的elType取值定义对应的elementConfig约束,再将所有情况联合为统一的表单项类型。

类型定义

// select类型表单项约束
interface SelectFormItem {
  key: string;
  label: string;
  elType: "select";
  elementConfig: {
    // 可根据categories的实际类型调整此处的options类型
    options: string[];
  }
}

// input类型表单项约束
interface InputFormItem {
  key: string;
  label: string;
  elType: "input";
  elementConfig: {
    // 可根据业务支持的input类型扩展字面量取值
    type: "text" | "number" | "email" | "password";
    placeholder?: string;
  }
}

// 联合得到总表单项类型
type FormItem = SelectFormItem | InputFormItem;

使用示例

// 示例categories数据,可替换为实际业务类型
const categories: string[] = ["前端开发", "后端开发", "产品设计", "运营"];

// 给inputGroup添加FormItem[]类型约束即可
const inputGroup: FormItem[] = [
  {
    key: "primary_category",
    label: "Primary Category",
    elType: "select",
    elementConfig: {
      options: categories,
    },
  },
  {
    key: "extra_tags",
    label: "Extra tags",
    elType: "input",
    elementConfig: {
      type: "text",
      placeholder: "e.g. startup, analytics, svelte, seo, social media,",
    },
  },
]

效果说明

  • 当elType取值为select时,elementConfig必须传入options属性,传入其他不属于select配置的属性会直接触发TS类型报错
  • 当elType取值为input时,elementConfig必须传入type属性,可选择传入placeholder,传入options等不属于input配置的属性会直接报错
  • 后续需要新增其他表单项类型(如textarea、radio、checkbox等),仅需新增对应的类型定义加入FormItem联合类型即可,扩展性强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:06:04