TypeScript实现React表单组件interface中type为select时options必填
实现方案
你可以通过 TypeScript 的可辨识联合类型实现该需求,调整后的属性定义如下:
// 提取通用基础属性 interface BaseFieldProps { name: string; label: string; } // 非select类型字段属性 interface NormalFieldProps extends BaseFieldProps { type: "email" | "text" | "textarea"; options?: string[]; } // select类型字段属性,options强制必填 interface SelectFieldProps extends BaseFieldProps { type: "select"; options: string[]; } // 最终导出的组件属性类型为两类的联合 type FieldProps = NormalFieldProps | SelectFieldProps;
校验效果说明
定义完成后TypeScript会自动根据type字段的取值做类型校验:
type为email/text/textarea时,options为可选属性,缺失不会报错type为select时,options为必填属性,缺失会直接抛出类型错误,完全符合预期效果
你可以直接测试示例场景:
// 无报错 <Field name="email" label="Email" type="email"/> // 类型错误:缺少必填属性options <Field name="country" label="Country" type="select"/>
简写版本
如果不需要拆分多个接口,也可以直接用交叉联合的方式一步定义:
type FieldProps = { name: string; label: string; } & ( | { type: "email" | "text" | "textarea"; options?: string[] } | { type: "select"; options: string[] } )
内容的提问来源于stack exchange,提问作者Yoofi Brown-Pobee
相关产品推荐
相关产品推荐

