1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

'undefined' の可能性があるオブジェクトを呼び出すことはできません(Jest、React、TypeScript)

1
Last updated at Posted at 2025-01-05

問題

Jestでテストを作成していたところ、vsコード上でTypeScriptの以下エラーが出ました。

'undefined' の可能性があるオブジェクトを呼び出すことはできません。ts(2722)
(parameter) setData: React.Dispatch<React.SetStateAction<Record[]>> | undefined
App.tsx
// 省略

// useStateの定義
  const [data, setData] = useState<Record[]>([]);

// 省略

// 登録ボタン
<RegistrationDialog button="registration" setData={setData} fetchData={fetchData} />

// 省略

// 編集ボタン
<RegistrationDialog item={item} button="modifcation" setData={setData} fetchData={fetchData} />
RegistrationDialog.tsx
interface RegistrationDialogProps {
    item?: Record;
    button?: string;
    // Dispatch<SetStateAction<Record[]>>型
        // ReactのuseStateフックによって提供される状態更新関数の型
        // 状態を更新するための関数を表す
    // ?を使ったオプショナル(存在しても存在しなくても良い)ではNG
    setData?: Dispatch<SetStateAction<Record[]>>;
    // setData?: Dispatch<SetStateAction<Record[]>> | undefined;でもNG
    
    fetchData: () => void;
}

解決策

RegistrationDialog.tsx
interface RegistrationDialogProps {
    item?: Record;
    button?: string;
    // 修正後
    setData: Dispatch<SetStateAction<Record[]>>;
    fetchData: () => void;
}

終わりに

対象ファイルを全部コピーし、出ているエラーをChatGPTに聞いたらすぐに解決できました。
許される状況であれば、この聞き方も良さそうです。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?