TypeScript NonNullable<T>ユーティリティ型の解説

NonNullable<T>が型からnullとundefinedを除外する方法を学びます。厳密なnullチェックと型の絞り込みの実践的な例を紹介します。

Union Types

詳細な説明

NonNullableの理解

NonNullable<T>Tからnullundefinedを除外した型を構築します。Excludeの特殊な形式です。

構文

type NonNullable<T> = Exclude<T, null | undefined>;
// 以下と同等:
type NonNullable<T> = T & {};

基本的な例

type MaybeString = string | null | undefined;
type DefiniteString = NonNullable<MaybeString>;
// 結果: string

type Mixed = string | number | null | undefined | boolean;
type NonNullMixed = NonNullable<Mixed>;
// 結果: string | number | boolean

実践パターン: Nullチェック後

function processValue<T>(value: T | null | undefined): NonNullable<T> {
  if (value == null) {
    throw new Error("Value is required");
  }
  return value as NonNullable<T>;
}

Array.filter()との使用

null値を配列からフィルタリングする一般的なパターン:

const items: (string | null)[] = ["a", null, "b", null, "c"];

// NonNullableなし -- TypeScriptはまだnullが存在する可能性があると考える
const filtered = items.filter((x) => x !== null);
// 型: (string | null)[]

// NonNullable型述語付き
const safe = items.filter(
  (x): x is NonNullable<typeof x> => x !== null
);
// 型: string[]

マップ型での使用

type RequiredNonNull<T> = {
  [K in keyof T]-?: NonNullable<T[K]>;
};

ユースケース

NonNullable<T>はstrictNullChecksが有効な状態で値がnon-nullとしてバリデーション済みであることを表明する必要がある場合に使用します。バリデーション層、配列フィルタリング、ガード句の後で一般的です。

試してみる — TypeScript Utility Types

フルツールを開く