[Next.js] useFormStateで “Types of property ‘message’ are incompatible.” というエラーが発生する時の解決方法

Next.js

Next.jsのuseFormStateで “Types of property ‘message’ are incompatible. Type ‘null’ is not assignable to type ‘string’.” というエラーが発生する時の解決方法について説明します。

広告

先程、Learn Next.jsのコードを写経していたら、useFormStateでエラーが発生しました。

Types of property ‘message’ are incompatible. Type ‘null’ is not assignable to type ‘string’.
‘message’プロパティの型に互換性がありません。null型はstring型に代入できません。

写経したコードは、バリデーションチェックを実装しているコードです。

Learn Next.js: Improving Accessibility | Next.js

解決方法

// create-form.tsx
const initialState = { message: null, errors: {} };
const [state, dispatch] = useFormState(createInvoice, initialState); // Error

useFormStateの型を指定したら、エラーを解消できました。

// create-form.tsx
const initialState = { message: null, errors: {} };
const [state, dispatch] = useFormState<State, FormData>(createInvoice, initialState);
// actions.ts
export type State = {
  errors?: {
    customerId?: string[];
    amount?: string[];
    status?: string[];
  };
  message?: string | null;
};

export async function createInvoice(prevState: State, formData: FormData) {
  // ...
}

参考ページ

typescript – Can't set React useFormState type property to null despite having set null as an option – Stack Overflow

広告