言語
日本語
English

Caution

お使いのブラウザはJavaScriptが無効になっております。
当サイトでは検索などの処理にJavaScriptを使用しています。
より快適にご利用頂くため、JavaScriptを有効にしたうえで当サイトを閲覧することをお勧めいたします。

TypeScript辞典

  1. トップページ
  2. TypeScript辞典
  3. Exclude<T, U> / Extract<T, U>

Exclude<T, U> / Extract<T, U>

対応: TypeScript 2.8(2018)

『Exclude<T, U>』と『Extract<T, U>』は、ユニオン型をフィルタリングするユーティリティ型です。『Exclude』は U に含まれる型を T から除外し、『Extract』は T と U の両方に含まれる型だけを取り出します。

構文

Exclude<T, U> // T から U に代入可能な型を除外
Extract<T, U> // T から U に代入可能な型だけを抽出

型一覧

概要
Exclude<T, U>T のユニオンから、U に代入可能な型を除いた型を返す。
Extract<T, U>T のユニオンのうち、U に代入可能な型だけを残した型を返す。

サンプルコード

type A = string | number | boolean;

// Exclude: boolean を除外
type WithoutBool = Exclude<A, boolean>;
// => string | number

// Extract: string だけ抽出
type OnlyString = Extract<A, string>;
// => string

// 複数の型を除外
type WithoutStrNum = Exclude<A, string | number>;
// => boolean

// 判別ユニオンへの応用
type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number }
  | { kind: 'triangle'; base: number };

type CircleOrSquare = Extract<Shape, { kind: 'circle' | 'square' }>;
// => { kind: 'circle'; radius: number } | { kind: 'square'; side: number }

type NotTriangle = Exclude<Shape, { kind: 'triangle' }>;
// => { kind: 'circle'; radius: number } | { kind: 'square'; side: number }

概要

『Exclude<T, U>』と『Extract<T, U>』は、どちらも条件型(Conditional Types)を使って実装されています。内部実装は次のとおりです。

type Exclude<T, U> = T extends U ? never : T;
type Extract<T, U> = T extends U ? T : never;

ユニオン型に対してこれらを適用すると、TypeScript はユニオンの各メンバーに対して条件を評価し(分配的条件型)、結果をユニオンとして返します。特定のイベント名・ステータス文字列・判別ユニオンのタグを絞り込む場面でよく使われます。

記事の間違いや著作権の侵害等ございましたらお手数ですがまでご連絡頂ければ幸いです。