联合类型与React Hook Form

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

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。

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 &#39;./Form&#39;;
import { useForm } from &#39;react-hook-form&#39;;
import { FormA, FormB } from &#39;./FormTypes&#39;;
import { UseFormSetValue } from &#39;react-hook-form/dist/types&#39;;

type FormType = FormA | FormB;
export default function App() {
  const { setValue } = useForm({
    defaultValues: { value: &#39;test&#39; } as unknown as FormA,
  });

  return (
    &lt;Form
      setValue={setValue as UseFormSetValue&lt;FormType&gt;}
      formObject={{ name: &#39;Jan&#39;, code: 10, key: &#39;string&#39; }}
    /&gt;
  );
}

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:

确定