MeWrite Docs

TypeError: Cannot read properties of null

nullオブジェクトのプロパティにアクセスしようとした際に発生するTypeError

概要

TypeError: Cannot read properties of null は、null の値に対してプロパティやメソッドにアクセスしようとした際に発生するランタイムエラーです。JavaScript/TypeScriptで最も頻繁に遭遇するエラーの一つで、非同期データの未ロード状態やDOM要素の取得失敗が主な原因です。

エラーメッセージ

TypeError: Cannot read properties of null (reading 'value')
TypeError: Cannot read properties of null (reading 'addEventListener')
TypeError: Cannot read properties of null (reading 'map')

原因

  1. null/undefinedへのプロパティアクセス: 変数がnullであることを確認せずにプロパティへアクセスしている
  2. 非同期データの未ロード: APIレスポンスが返る前にデータを参照している
  3. DOM要素の取得失敗: document.getElementById() などが要素を見つけられずnullを返している
  4. React/Vueのstate初期値がnull: 初期レンダリング時にnull状態のデータを参照している
  5. JSONパース結果の想定外の構造: ネストされたプロパティが存在しない

解決策

1. オプショナルチェーン(?.)を使う

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// ❌ エラー
const name = user.profile.name;

// ✅ オプショナルチェーンで安全にアクセス
const name = user?.profile?.name;

// メソッド呼び出しにも使える
const result = obj?.method?.();

// 配列アクセスにも使える
const first = arr?.[0]?.name;

2. nullチェックを追加する

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// ❌ エラー
function processUser(user: User | null) {
  console.log(user.name);
}

// ✅ nullチェックを先に行う
function processUser(user: User | null) {
  if (user === null) {
    console.log("ユーザーが見つかりません");
    return;
  }
  console.log(user.name); // ここではuserはUser型に絞り込まれる
}

3. DOM要素の取得を安全に行う

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// ❌ エラー: 要素が存在しない場合にnullが返る
const element = document.getElementById("my-input");
element.addEventListener("click", handler);

// ✅ 存在チェックを行う
const element = document.getElementById("my-input");
if (element) {
  element.addEventListener("click", handler);
}

// ✅ TypeScriptでは非nullアサーション(要素の存在が確実な場合のみ)
const element = document.getElementById("my-input")!;

4. Reactでの条件付きレンダリング

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// ❌ エラー: dataがnullの間にアクセスしてしまう
function UserProfile() {
  const [data, setData] = useState<User | null>(null);

  useEffect(() => {
    fetchUser().then(setData);
  }, []);

  return <div>{data.name}</div>; // 初回レンダリングでエラー
}

// ✅ 条件付きレンダリングで安全に表示
function UserProfile() {
  const [data, setData] = useState<User | null>(null);

  useEffect(() => {
    fetchUser().then(setData);
  }, []);

  if (!data) {
    return <div>Loading...</div>;
  }

  return <div>{data.name}</div>;
}

5. Null合体演算子(??)でデフォルト値を設定

1
2
3
4
5
6
7
8
9
// ❌ エラーの可能性
const value = response.data.items.length;

// ✅ デフォルト値を設定
const items = response?.data?.items ?? [];
const value = items.length;

// ✅ 関数の戻り値にも使える
const config = getConfig() ?? { timeout: 3000 };

関連エラー

JavaScript の他のエラー

最終更新: 2026-02-03