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
相关产品推荐
相关产品推荐

