Null 安全性
null 参照エラーを型システムで防止し、null の可能性がある値を明示的に扱うプログラミング言語の機能
型システムセキュリティ
Null 安全性とは
Null 安全性 (Null Safety) は、null 参照エラー (NullPointerException, TypeError: Cannot read properties of null) を型システムで防止するプログラミング言語の機能である。Tony Hoare が null 参照の発明を「10 億ドルの過ち」と呼んだように、null は最も多いバグの原因の 1 つだ。
TypeScript の strictNullChecks
TypeScript の strictNullChecks を有効にすると、null と undefined が通常の型に含まれなくなる。
// strictNullChecks: true
function getUser(id: string): User | null {
return db.find(id) ?? null;
}
const user = getUser('123');
// user.name; // ❌ コンパイルエラー: Object is possibly 'null'
if (user) {
user.name; // ✅ OK: null チェック後は User 型に絞り込まれる
}
// Optional Chaining
const name = user?.name; // string | undefined
const city = user?.address?.city; // string | undefined
// Nullish Coalescing
const displayName = user?.name ?? 'Anonymous'; // string
言語ごとの Null 安全性
| 言語 | 仕組み | null の扱い |
|---|---|---|
| TypeScript | strictNullChecks |
T | null で明示 |
| Rust | Option<T> |
null が存在しない |
| Kotlin | String? (Nullable 型) |
? で明示 |
| Swift | String? (Optional) |
? で明示 |
| Java | Optional<T> |
ライブラリレベル (言語レベルではない) |
Rust は言語レベルで null が存在せず、Option<T> (Some(value) or None) で値の有無を表現する。パターンマッチで網羅的に処理するため、null チェックの漏れが原理的に発生しない。
TypeScript での実践パターン
Non-null Assertion の回避
// ❌ Non-null Assertion (!): null チェックをスキップ (危険)
const user = getUser('123')!; // null なら実行時エラー
// ✅ 明示的な null チェック
const user = getUser('123');
if (!user) throw new Error('User not found');
// この行以降、user は User 型に絞り込まれる
Optional Chaining と Nullish Coalescing
// ❌ 冗長な null チェック
const city = user && user.address && user.address.city ? user.address.city : 'Unknown';
// ✅ Optional Chaining + Nullish Coalescing
const city = user?.address?.city ?? 'Unknown';
関数の戻り値で null を避ける
// ❌ null を返す: 呼び出し側が null チェックを忘れるリスク
function findUser(id: string): User | null { /* ... */ }
// ✅ 例外をスロー: 見つからない場合は明示的にエラー
function getUserOrThrow(id: string): User {
const user = db.find(id);
if (!user) throw new NotFoundError(`User ${id} not found`);
return user;
}
strictNullChecks を有効にする
{
"compilerOptions": {
"strict": true // strictNullChecks を含む全 strict オプションを有効化
}
}
既存プロジェクトで有効化すると大量のエラーが出るが、段階的に修正する価値がある。null 関連のバグが劇的に減る。
現場での応用を知るには関連書籍も役立つ。