TypeScriptでよく遭遇する「Cannot read property 'X' of undefined」や「Object is possibly 'undefined'」といったエラーを効果的に回避する方法として、オプショナルチェイニング(?.)とNullish Coalescing(??)演算子の活用方法を詳しく解説します。

オプショナルチェイニング(?.)とは

オプショナルチェイニングは、オブジェクトのプロパティに安全にアクセスするための演算子です。プロパティが存在しない場合でもエラーを発生させず、`undefined`を返します。

// 従来の方法
const userName = user && user.profile && user.profile.name;

// オプショナルチェイニングを使用
const userName = user?.profile?.name;

Nullish Coalescing(??)演算子とは

Nullish Coalescing演算子は、左辺の値が`null`または`undefined`の場合にのみ、右辺の値を返す演算子です。

// 従来の方法(||演算子)
const value = someValue || 'default';

// Nullish Coalescingを使用
const value = someValue ?? 'default';

実践的な使用例

1. ネストされたオブジェクトの処理

interface User {
  profile?: {
    address?: {
      city?: string;
    };
  };
}

const user: User = {};

// 安全にアクセス
const city = user?.profile?.address?.city ?? 'Unknown City';

2. 配列要素へのアクセス

const array: number[] | undefined = undefined;
const firstElement = array?.[0] ?? -1;

3. メソッド呼び出し

interface API {
  fetch?: () => Promise<string>;
}

const api: API = {};
const result = await api.fetch?.() ?? 'Failed to fetch';

ベストプラクティス

1. 早期リターンとの組み合わせ

function processUser(user?: User) {
  if (!user?.profile) return 'No profile';
  return user.profile.name ?? 'Anonymous';
}

2. デフォルト値の設定

const config = {
  timeout: settings?.timeout ?? 5000,
  retries: settings?.retries ?? 3
};

3. 条件付きレンダリング(Reactの例)

return (
  <div>
    {user?.isAdmin && <AdminPanel />}
    <span>{user?.profile?.name ?? 'Guest'}</span>
  </div>
);

注意点

  • オプショナルチェイニングは過度に使用すると、コードの可読性が低下する可能性があります
  • Nullish Coalescingは`false`や`0`などの偽値を保持したい場合に特に有用です
  • TypeScriptの strict nullチェックを有効にすることで、より安全なコードを書くことができます

まとめ

オプショナルチェイニングとNullish Coalescing演算子は、TypeScriptでの安全なプロパティアクセスを実現する強力なツールです。これらを適切に使用することで、より堅牢で保守性の高いコードを書くことができます。

また、これらの機能はモダンなJavaScriptでも使用可能であり、クロスブラウザ対応も良好です。型安全性を保ちながら、簡潔で読みやすいコードを書くための重要な機能として、積極的に活用することをお勧めします。