TypeScript中react-select结合react-hook-form的类型错误求助
解决react-select与react-hook-form结合的类型不匹配问题
错误根源
react-select默认的OptionsOrGroups类型要求选项的value为string类型,但你的代码中unit.id是number类型;同时filterModel.data?.units可能为undefined,导致生成的选项数组类型是{ label: string; value: number }[] | undefined,和react-select期望的类型不兼容。
解决步骤
1. 定义自定义选项类型
先声明匹配你数据结构的选项类型,明确value为number:
type UnitOption = { label: string; value: number; };
2. 给Select组件指定泛型
在使用Select时,通过泛型明确它接收的选项类型,以及开启多选(对应isMulti={true}):
<Select<UnitOption, true> {...field} placeholder={translate("Select organization")} options={filterModel.data?.units.map(unit => ({ label: unit.name, value: unit.id })) ?? []} isMulti closeMenuOnSelect={false} />
3. 确保options始终为数组类型
通过?? []给map结果设置默认空数组,避免出现undefined,让类型检查更安全。
4. 给react-hook-form指定表单类型(可选但推荐)
初始化useForm时明确表单字段的类型,让类型校验更严格:
const { control, handleSubmit } = useForm<{ Units: number[]; // 开启多选后,字段值为number数组 }>();
完整修改后的代码示例
import { useForm, Controller } from "react-hook-form"; import Select from "react-select"; type UnitOption = { label: string; value: number; }; export const YourComponent = () => { const { control, handleSubmit } = useForm<{ Units: number[] }>(); const filterModel = /* 你的filterModel数据源 */; const translate = (key: string) => key; // 替换为你的国际化函数 const applyFilter = (data: { Units: number[] }) => { // 编写表单提交逻辑 }; return ( <Form onSubmit={handleSubmit(applyFilter)}> <FormLabel>Organization</FormLabel> <Controller name="Units" control={control} render={({ field }) => ( <Select<UnitOption, true> {...field} placeholder={translate("Select organization")} options={filterModel.data?.units.map(unit => ({ label: unit.name, value: unit.id })) ?? []} isMulti closeMenuOnSelect={false} /> )} /> </Form> ); };
内容的提问来源于stack exchange,提问作者dasper
相关产品推荐
相关产品推荐

