React-Hook-Form 中 setValue 出现 Argument of type ‘string‘ is not assignable to parameter of type never

时间:2025-02-17 20:18:27

在使用 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 {
  []: { firstName: string; lastName: string };
  []: 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 才能正確解析  的型別
    setValue('', 'PJCHENder');
  }, [setValue]);

  //...
}

Reference

[1] /react/note-react-hook-form/