在使用 React-Hook-Form 中,使用 setValue 方法出现:
Argument of type 'string' is not assignable to parameter of type 'never'.
主要是因为使用了 enum:
// ❌ 使用一般的 enum 在使用 setValue 是會出現錯誤
enum UserField {
USERNAME = 'username',
EMAIL = 'email',
}
interface PersonalInfo {
[UserField.USERNAME]: { firstName: string; lastName: string };
[UserField.EMAIL]: string;
}
改用使用 object 搭配 as const:
// ✅ 使用 Object as const
const UserField = {
USERNAME: 'username',
EMAIL: 'email',
} as const;
interface PersonalInfo {
[UserField.USERNAME]: { firstName: string; lastName: string };
[UserField.EMAIL]: string;
}
export default function App() {
// ...
useEffect(() => {
// react-hook-form 才能正確解析 username.firstName 的型別
setValue('username.firstName', 'PJCHENder');
}, [setValue]);
//...
}
Reference
[1] https://pjchender.dev/react/note-react-hook-form/
本文介绍了在使用React Hook Form时遇到的类型错误`Argument of type 'string' is not assignable to parameter of type 'never'`,并提供了解决方案。问题源于使用enum定义的类型不匹配,通过将enum替换为使用`as const`修饰的对象可以正确解析username.firstName的类型。在示例中,更新UserField为常量对象并调整PersonalInfo接口后,setValue方法能正确识别属性。

被折叠的 条评论
为什么被折叠?



