英文:
Union types with React Hook Form
问题
我有一个组件,应该可以在2个或更多的表单中重复使用。我将setValue prop方法从react-form-hook传递给组件。我尝试使用联合类型UseFormSetValue<FormAType | FormBType>
来定义它。
但这会导致TS在其中一个组件上抱怨,因为另一个对象中可能不存在某些属性。
重现仓库: https://stackblitz.com/edit/stackblitz-starters-meufv5?file=src%2FApp.tsx
为什么联合类型不像我期望的那样工作?应该接受A或B吗?
有没有一个好的解决方法?
英文:
I have a component that should be able to be reused for 2 or more forms. I pass down the setValue prop method from react-form-hook down to the component. I've tried typing it with an union type UseFormSetValue<FormAType | FormBType>
.
But this makes TS complain on one of the components that either properties are not present in the other object.
Reproduction repo: https://stackblitz.com/edit/stackblitz-starters-meufv5?file=src%2FApp.tsx
Why is the union type not working like I would expect? Accept either A or B?
Is there a good workaround for this?
答案1
得分: 2
我们需要定义一个FormA和FormB的联合类型,称为FormType。setValue函数被显式地转换为**UseFormSetValue<FormType>**以匹配更新后的FormType定义。这确保了setValue函数可以正确处理FormA和FormB。
import Form from './Form';
import { useForm } from 'react-hook-form';
import { FormA, FormB } from './FormTypes';
import { UseFormSetValue } from 'react-hook-form/dist/types';
type FormType = FormA | FormB;
export default function App() {
const { setValue } = useForm({
defaultValues: { value: 'test' } as unknown as FormA,
});
return (
<Form
setValue={setValue as UseFormSetValue<FormType>}
formObject={{ name: 'Jan', code: 10, key: 'string' }}
/>
);
}
英文:
We need to define a union type of FormA and FormB as FormType. The setValue function is explicitly cast to UseFormSetValue<FormType> to match the updated FormType definition. This ensures that both FormA and FormB can be handled properly by the setValue function.
import Form from './Form';
import { useForm } from 'react-hook-form';
import { FormA, FormB } from './FormTypes';
import { UseFormSetValue } from 'react-hook-form/dist/types';
type FormType = FormA | FormB;
export default function App() {
const { setValue } = useForm({
defaultValues: { value: 'test' } as unknown as FormA,
});
return (
<Form
setValue={setValue as UseFormSetValue<FormType>}
formObject={{ name: 'Jan', code: 10, key: 'string' }}
/>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论