MeWrite Docs

Object is possibly 'undefined'

TypeScriptでオブジェクトがundefinedの可能性がある場合のエラー

概要

Object is possibly 'undefined' は、TypeScriptのstrictNullChecksが有効な場合に、undefinedの可能性があるオブジェクトのプロパティやメソッドにアクセスしようとすると発生するエラーです。

エラーメッセージ

TS2532: Object is possibly 'undefined'.
TS18048: 'user' is possibly 'undefined'.
TS2533: Object is possibly 'null' or 'undefined'.

原因

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
interface User {
  name: string;
  email: string;
}

function getUser(id: number): User | undefined {
  // ...
}

const user = getUser(1);
console.log(user.name);  // Error: Object is possibly 'undefined'

解決策

1. if文でundefinedチェック

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const user = getUser(1);

if (user) {
  console.log(user.name);  // OK: userはUser型に絞り込まれる
}

// または
if (user !== undefined) {
  console.log(user.name);
}

2. オプショナルチェーン(?.)

1
2
3
4
5
6
7
const user = getUser(1);

// undefinedならundefinedを返す
console.log(user?.name);  // string | undefined

// ネストしたプロパティ
console.log(user?.address?.city);

3. Null合体演算子(??)

1
2
3
4
5
const user = getUser(1);

// デフォルト値を指定
const name = user?.name ?? 'Unknown';
console.log(name);  // string

4. 非nullアサーション演算子(!)

1
2
3
4
5
6
7
8
const user = getUser(1);

// undefinedでないことが確実な場合のみ使用
console.log(user!.name);  // 危険: 実行時エラーの可能性

// より安全: 事前にチェックしてから
if (!user) throw new Error('User not found');
console.log(user.name);  // 以降userはUser型

5. 型ガード関数

1
2
3
4
5
6
7
8
9
function isDefined<T>(value: T | undefined | null): value is T {
  return value !== undefined && value !== null;
}

const user = getUser(1);

if (isDefined(user)) {
  console.log(user.name);  // OK
}

6. アサーション関数(TypeScript 3.7+)

1
2
3
4
5
6
7
8
9
function assertDefined<T>(value: T | undefined, message?: string): asserts value is T {
  if (value === undefined) {
    throw new Error(message ?? 'Value is undefined');
  }
}

const user = getUser(1);
assertDefined(user, 'User not found');
console.log(user.name);  // OK: 以降userはUser型

よくあるパターン

配列のfind

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];

// findはundefinedを返す可能性がある
const user = users.find(u => u.id === 3);
console.log(user.name);  // Error

// 解決策
const user = users.find(u => u.id === 1);
if (user) {
  console.log(user.name);
}

// または
const user = users.find(u => u.id === 1) ?? { id: 0, name: 'Unknown' };
console.log(user.name);  // OK

Map.get

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const userMap = new Map<number, User>();

// getはundefinedを返す可能性がある
const user = userMap.get(1);
console.log(user.name);  // Error

// 解決策
const user = userMap.get(1);
if (user) {
  console.log(user.name);
}

オプショナルプロパティ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
interface Config {
  api?: {
    baseUrl?: string;
  };
}

const config: Config = {};

// ネストしたオプショナルプロパティ
const url = config.api.baseUrl;  // Error: config.api is possibly undefined

// 解決策
const url = config.api?.baseUrl ?? 'http://localhost';

配列のインデックスアクセス

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const items = ['a', 'b', 'c'];

// noUncheckedIndexedAccess が有効な場合
const item = items[5];  // string | undefined
console.log(item.toUpperCase());  // Error

// 解決策
const item = items[5];
if (item) {
  console.log(item.toUpperCase());
}

tsconfig.jsonの設定

1
2
3
4
5
6
7
{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true,
    "noUncheckedIndexedAccess": true
  }
}

型の絞り込み

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function processUser(user: User | undefined) {
  // 早期リターン
  if (!user) {
    return;
  }

  // 以降、userはUser型として扱われる
  console.log(user.name);
  console.log(user.email);
}

関連エラー

関連エラー

TypeScript の他のエラー

最終更新: 2025-12-24