TypeScript で「Object is possibly 'null'」が解消できない
strictNullChecks 有効下では null/undefined を含む型のプロパティアクセスにナローイングが要る。
早期 return / オプショナルチェイン / 非 null アサーションを場面ごとに使い分ける。
公開: 更新:
要約
Object is possibly 'null'. は strictNullChecks 下で null / undefined を含む型 に対し、ナローイングなしでプロパティアクセスしたときに出る。
早期 return で型を狭める、?. で安全アクセス、最後の手段として ! を使う、の 3 系統を場面で使い分ければ素直に解消する。
よくある原因
- strictNullChecks 有効:
strict: trueで連動し、null/undefinedが型に明示的に含まれる(tsconfig 公式(新しいタブで開く)) - DOM API の戻り値:
document.querySelector('.x')はElement | null、canvas.getContext('2d')もnullを含む - ライブラリ API の undefined:
useRef<HTMLDivElement>(null)の.currentやMap<K, V>#getはT | undefined - 判定漏れ: 一度 null チェックしても、別の if スコープに入るとナローイングが効かなくなり再度警告が出る
解決策
1. 早期 return でナローイング
const el = document.querySelector(".target");
if (!el) return;
el.classList.add("active"); // ここでは Element 型に絞られる公式の Narrowing ドキュメント(新しいタブで開く) のとおり、if (!x) return の後ろでは型が狭まる。
2. オプショナルチェインと nullish coalescing
const text = el?.textContent ?? "";
user.profile?.name?.toUpperCase();?. は途中で null / undefined に当たれば全体を undefined にする。?? で既定値を埋めれば後段の処理がそのまま書ける。
3. 非 null アサーション(最終手段)
const root = document.getElementById("root")!; // null では無いと断言呼ぶ側が存在を保証できる場面に限って使う。
多用すると本来の null チェックを蝕むため、レビューで歯止めをかける。
4. 型ガード関数で再利用する
function isNonNull<T>(v: T | null | undefined): v is T {
return v !== null && v !== undefined;
}
const items = [1, null, 2, undefined].filter(isNonNull);
// ^? number[]v is T で書く述語型は複数箇所で同じ条件を再利用するときに便利。Array#filter と組み合わせると型も自然に狭まる。
実行例
実際に上記の手順を node:20(Debian GNU/Linux 12)環境で動かすと、TypeScript 5.9.3 のコンパイラが src/bad.ts(2,1): error TS2531: Object is possibly 'null'. を出力し(終了コード 2)、早期 return およびオプショナルチェイン+nullish coalescing のいずれの解消策を適用しても終了コード 0 となることが確かめられた。
Version 5.9.3$ npx tsc
src/bad.ts(2,1): error TS2531: Object is possibly 'null'.
tsc 終了コード: 2$ npx tsc
tsc 終了コード: 0$ npx tsc
tsc 終了コード: 0— 2026-08-02 時点の出力