联合类型与React Hook Form

huangapple go评论129阅读模式
英文:

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

我们需要定义一个FormAFormB的联合类型,称为FormType。setValue函数被显式地转换为**UseFormSetValue<FormType>**以匹配更新后的FormType定义。这确保了setValue函数可以正确处理FormA和FormB。

  1. import Form from './Form';
  2. import { useForm } from 'react-hook-form';
  3. import { FormA, FormB } from './FormTypes';
  4. import { UseFormSetValue } from 'react-hook-form/dist/types';
  5. type FormType = FormA | FormB;
  6. export default function App() {
  7. const { setValue } = useForm({
  8. defaultValues: { value: 'test' } as unknown as FormA,
  9. });
  10. return (
  11. <Form
  12. setValue={setValue as UseFormSetValue<FormType>}
  13. formObject={{ name: 'Jan', code: 10, key: 'string' }}
  14. />
  15. );
  16. }
英文:

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.

  1. import Form from &#39;./Form&#39;;
  2. import { useForm } from &#39;react-hook-form&#39;;
  3. import { FormA, FormB } from &#39;./FormTypes&#39;;
  4. import { UseFormSetValue } from &#39;react-hook-form/dist/types&#39;;
  5. type FormType = FormA | FormB;
  6. export default function App() {
  7. const { setValue } = useForm({
  8. defaultValues: { value: &#39;test&#39; } as unknown as FormA,
  9. });
  10. return (
  11. &lt;Form
  12. setValue={setValue as UseFormSetValue&lt;FormType&gt;}
  13. formObject={{ name: &#39;Jan&#39;, code: 10, key: &#39;string&#39; }}
  14. /&gt;
  15. );
  16. }

huangapple
  • 本文由 发表于 2023年7月13日 19:42:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定