Discriminated Union(判別可能なユニオン型、タグ付きユニオン)は、取りうる種類を固定し、どの種類かを示すタグで値を区別する型です。TypeScriptでは、すべてのメンバーが同じ名前のリテラル型プロパティを持つオブジェクト型のユニオンとして書き、この値を比べるだけで対応するメンバーへ型を絞り込めます。成立条件、never による網羅性チェック、絞り込みが効かない原因を、TypeScript 7.0.2 で実際に出たエラー文言つきで整理し、後半ではPython・C# 15・F#・Rustで網羅漏れがどう報告されるかを実測で並べます。
まとめ:Discriminated Unionの要点
- 成立条件は「ユニオンの全メンバーが、共通の名前のプロパティをリテラル型で持つこと」。
kind: stringのように型が広がっていると絞り込みは効きません(TS2339)。 default節でnever型の変数へ代入しておくと、メンバーを足したのに分岐を書き忘れた箇所が、不足メンバー名つきのエラー(TS2322)になります。- 分割代入や「条件を変数に保存する」書き方でも絞り込みは効きますが、
constか再代入しない引数であることが条件です。letで受けると効きません。 - 外から届くJSONは型では守れないので、Zodの
z.discriminatedUnionやPydanticのdiscriminatorで実行時にも検証します。素のユニオンより失敗箇所の報告がはっきり絞られます。 - C# 15(.NET 11)の
unionとF#の判別共用体は、網羅漏れを警告(CS8509・FS0025)で報告します。ビルドを止めたいなら警告をエラーに格上げします。Rustのmatchは最初からエラー(E0004)です。
Discriminated Union(判別可能なユニオン型)の成立条件
TypeScript公式ハンドブックのNarrowingの章は、この型を次のように定義しています。
When every type in a union contains a common property with literal types, TypeScript considers that to be a discriminated union, and can narrow out the members of the union.
条件は共通プロパティが「リテラル型」であることです。この共通プロパティを判別プロパティ(discriminant、ディスクリミネータ)と呼び、慣習的に kind・type・status といった名前を付けます。
通常のユニオン型との絞り込み結果の違い
まず判別プロパティをリテラル型で定義した場合です。
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };
type Shape = Circle | Square;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}
これは tsc --strict --noEmit がエラーなしで通ります。戻り値を number と宣言しているのに default 節も末尾の return も無いまま通るのは、2つの case でユニオンを使い切ったとコンパイラが判断しているためです。
次に、判別プロパティの型だけを string に変えます。
type Circle = { kind: string; radius: number };
type Square = { kind: string; size: number };
type Shape = Circle | Square;
function area(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
}
return shape.size ** 2;
}
TypeScript 7.0.2 は次のエラーを返します。
error TS2339: Property 'radius' does not exist on type 'Shape'.
Property 'radius' does not exist on type 'Square'.
error TS2339: Property 'size' does not exist on type 'Shape'.
Property 'size' does not exist on type 'Circle'.
比較式 shape.kind === "circle" そのものは受理され、弾かれるのはその後の shape.radius のように片方のメンバーにしかないプロパティへのアクセスです。判別プロパティは必ずリテラル型で書いてください。
判別プロパティに使えるboolean・enum・テンプレートリテラル型
判別プロパティは文字列リテラルに限りません。成功と失敗の2値なら boolean のリテラル型が簡潔です。
type Ok = { ok: true; value: number };
type Err = { ok: false; error: string };
type Result = Ok | Err;
function show(r: Result): string {
return r.ok ? String(r.value) : r.error;
}
文字列enumのメンバ(Kind.Circle の形)を判別プロパティの型にした定義も、case Kind.Circle: で絞り込めます。TypeScript 4.5 からは、`${string}Error` のようなテンプレートリテラル型も判別子として扱われます(4.5のリリースノート)。
type Ok = { type: "ok"; value: number };
type Fail = { type: `${string}Error`; message: string };
type R = Ok | Fail;
function show(r: R): string {
if (r.type === "ok") return String(r.value);
return r.message;
}
const e: R = { type: "TimeoutError", message: "timeout" };
これも --strict で通り、"TimeoutError" や "NetworkError" を1つのメンバーで受けられます。
判別プロパティを追加できない型のin演算子による絞り込み
外部APIの型など、判別プロパティを後から足せない場合は、in 演算子でプロパティの有無から絞り込めます。
type Shape = { radius: number } | { size: number };
function area(shape: Shape): number {
if ("radius" in shape) return Math.PI * shape.radius ** 2;
return shape.size ** 2;
}
この形でもメンバー追加は検出できます。ユニオンに { base: number } を足すと、最後の shape.size が error TS2339: Property 'size' does not exist on type '{ size: number; } | { base: number; }'. になります。自分で定義できる型なら判別プロパティを持たせるほうが簡潔です。IDとメールアドレスのような string の別名を区別したいだけなら、Branded Types(ブランド型)とは?TypeScriptの書き方とブランドが外れる落とし穴で扱うブランド型が合っています。
neverによるコンパイル時の網羅性検査
メンバーを増やしたときに「分岐を書き忘れた場所」をコンパイラに列挙させるのが、いちばん効く使い方です。ハンドブックのExhaustiveness checkingの節は never の性質を次のように説明しています。
The never type is assignable to every type; however, no type is assignable to never (except never itself).
すべての case を書き切っていれば、default 節に届く値の型は never になり、never 型の変数へ代入できます。書き漏らしがあると、残ったメンバーは never に代入できないのでエラーになります。
--strict だけでも一定の検出は働きます。先ほどの Shape に Triangle を足して分岐を2つのままにすると、TypeScript 7.0.2 は error TS2366: Function lacks ending return statement and return type does not include 'undefined'. を返します。ただしこのメッセージはどのメンバーを取りこぼしたかを示さず、戻り値の無い(void)関数では出ません。そこで never を使います。
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };
type Triangle = { kind: "triangle"; base: number; height: number };
type Shape = Circle | Square | Triangle;
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
default: {
const exhaustive: never = shape;
return exhaustive;
}
}
}
Triangle の分岐が無いため、TypeScript 7.0.2 はTS2366に代わって次を出力します。
error TS2322: Type 'Triangle' is not assignable to type 'never'.
不足メンバー名を名指しする点が実務で効きます。if の連鎖でも、最後に同じ代入を置けば同じ検査が働きます。逆に、default 節で return 0; のように何でも受け流すと、メンバーを足しても何も報告されません。網羅性検査を効かせたい分岐では、default を「その他」の受け皿に使わないでください。成功と失敗を1つの値で表すエラー処理への応用は鉄道指向プログラミング(ROP)とは|Result型のbind・mapと5言語の実装、使わない場面で扱っています。
ナローイングを妨げる型の拡大・分割代入・条件変数の制約
1. オブジェクトリテラルの型の拡大(widening)
判別プロパティの定義が正しくても、代入する値の型が string に広がっていると弾かれます。
const raw = { kind: "circle", radius: 2 };
const s: Shape = raw;
error TS2322: Type '{ kind: string; radius: number; }' is not assignable to type 'Shape'.
Type '{ kind: string; radius: number; }' is not assignable to type 'Circle'.
Types of property 'kind' are incompatible.
Type 'string' is not assignable to type '"circle"'.
中間変数を挟まず const s: Shape = { kind: "circle", radius: 2 }; と直接書くか、as const を付けてリテラル型を保てば通ります。最終行が「string は "circle" に代入できない」と原因を指しているので、まずこの行を読んでください。
2. 分割代入の対象プロパティと宣言方法の制約
TypeScript 4.6 の「Control Flow Analysis for Destructured Discriminated Unions」で、分割代入した判別プロパティでも絞り込みが効くようになりました。ただし条件があります。
type Action =
| { kind: "add"; payload: number }
| { kind: "note"; payload: string };
function run({ kind, payload }: Action): string {
if (kind === "add") return payload.toFixed(2);
return payload.toUpperCase();
}
これは通ります。一方、固有プロパティの名前がメンバーごとに違う場合は、分割代入の時点で失敗します。
type Result = { ok: true; value: number } | { ok: false; error: string };
function show({ ok, value, error }: Result): string {
return ok ? String(value) : error;
}
error TS2339: Property 'value' does not exist on type 'Result'.
error TS2339: Property 'error' does not exist on type 'Result'.
絞り込みが働く前に、ユニオン全体からプロパティを取り出そうとするためです。名前がメンバーごとに違うなら、分割代入せず r.ok で判定してから中身に触ります。宣言の仕方にも条件があり、同じ Action を let { kind, payload } = a; で受けると error TS2339: Property 'toFixed' does not exist on type 'string | number'. になります。引数で分割代入した変数を関数内で再代入した場合も同じです。
3. 判定結果を変数に保存したときのconstとletの差
TypeScript 4.4 から、判定結果を変数に入れてから if で使っても絞り込みが効きます。4.4のリリースノートは、対象が a const, a readonly property, or an un-modified parameter の場合に限ると書いています。ここでの Shape は冒頭の2メンバー版(Circle | Square)です。Triangle を足した3メンバー版では、const のままでも末尾の shape.size がTS2339になります。
function area(shape: Shape): number {
const isCircle = shape.kind === "circle";
if (isCircle) return Math.PI * shape.radius ** 2;
return shape.size ** 2;
}
これは通ります。const isCircle を let isCircle に変えるだけで、TypeScript 7.0.2 は shape.radius と shape.size の両方にTS2339を出します。const のままでも、判定のあとで shape 引数に別の値を代入すると error TS2339: Property 'radius' does not exist on type 'Square'. になります。長い条件に名前を付けて読みやすくするのはよい書き方ですが、const で受け、対象の変数を書き換えないことが前提です。
ハンドラのマップで分岐を1か所にまとめる書き方
同じ switch が何か所にも散らばってきたら、判別プロパティの値をキーにしたオブジェクトへ処理を寄せる方法があります。マップ型と Extract を組み合わせると、キーの抜けもコンパイラが見つけます。
type Handlers = {
[K in Shape["kind"]]: (s: Extract<Shape, { kind: K }>) => number;
};
const handlers: Handlers = {
circle: (s) => Math.PI * s.radius ** 2,
square: (s) => s.size ** 2,
};
Shape が3メンバーのままでは、TypeScript 7.0.2 は次を返します。
error TS2741: Property 'triangle' is missing in type '{ circle: (s: Circle) => number; square: (s: Square) => number; }' but required in type 'Handlers'.
ここで詰まりやすいのが呼び出し側です。handlers[s.kind](s) と素直に書くと、error TS2345: Argument of type 'Shape' is not assignable to parameter of type 'never'. になり、続く行に The intersection 'Circle & Square & Triangle' was reduced to 'never' と出ます。s.kind と s が同じメンバーを指すという対応をコンパイラが追えず、3つの関数のどれにも渡せる引数を求めた結果です。
この対応を保つには、メンバーの中身を先にマップとして定義し、ユニオンをそこから組み立てます。TypeScript 4.6のリリースノートの「Indexed Access Inference Improvements」とPR #47109で示された形です。
type ShapeMap = {
circle: { radius: number };
square: { size: number };
triangle: { base: number; height: number };
};
type Shape<K extends keyof ShapeMap = keyof ShapeMap> = {
[P in K]: { kind: P } & ShapeMap[P];
}[K];
const handlers: { [K in keyof ShapeMap]: (s: Shape<K>) => number } = {
circle: (s) => Math.PI * s.radius ** 2,
square: (s) => s.size ** 2,
triangle: (s) => (s.base * s.height) / 2,
};
function area<K extends keyof ShapeMap>(s: Shape<K>): number {
return handlers[s.kind](s);
}
console.log(area({ kind: "triangle", base: 4, height: 3 })); // 6
型アサーション無しでコンパイルが通り、実行すると 6 を出力します。Shape(型引数なし)は従来どおり3メンバーのユニオンなので、switch での絞り込みもそのまま使えます。分岐が少ないうちは switch と never のほうが読みやすいので、同じ分岐の重複で修正漏れが起き始め、マップ型の複雑さより処理を1か所に集める利点が上回ってから移すのが目安です。
実務での使いどころとZodによる実行時検証
Discriminated Unionが効くのは、同時には1つの状態しか取らないが、状態ごとに持つデータが違うものです。非同期処理の状態(読み込み中・成功・失敗)、APIレスポンス、UIイベント、Reduxのアクションが典型です。全フィールドをオプショナルにした型と違い、成功時の data と失敗時の error を必須にできます。ただしTypeScriptは構造的部分型なので、変数経由なら両方を持つ値も代入でき、余分なプロパティまで禁止する仕組みではありません。
type Fetch<T> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "failure"; error: Error };
型はコンパイル時のものなので、外から届くJSONそのものは守れません。Zod 4.6.7 で z.discriminatedUnion と通常の z.union に同じ不正データ({ kind: "circle", radius: "2" }、radiusが文字列)を通すと、返る issues が次のように変わります。
// z.discriminatedUnion("kind", [Circle, Square])
[ { "expected": "number", "code": "invalid_type", "path": ["radius"],
"message": "Invalid input: expected number, received string" } ]
// z.union([Circle, Square])
[ { "code": "invalid_union", "path": [], "message": "Invalid input",
"errors": [ [ /* circle枝: radius の型違い */ ],
[ /* square枝: kind が違う・size が無い */ ] ] } ]
z.discriminatedUnion は判別プロパティで枝を1つに決めてから検証するので、失敗箇所が radius だと一意に分かります。z.union は全部の枝の失敗を束ねるため、無関係なsquare枝のエラーまで入れ子で並びます。判別値そのものが想定外({ kind: "triangle" })なら、z.discriminatedUnion は path: ["kind"] に Invalid discriminator value. Expected 'circle' | 'square' を返します。Zodの導入はZodの使い方入門|npm install zodとz.infer・safeParse【最新4.6.7・脆弱性修正】を参照してください。状態を型で数え上げる設計を業務システムの画面とAPIに通して入れたい場合は、フルスクラッチのシステム開発として設計段階から相談いただけます。
Pythonのdiscriminated union:Pydanticの実行時検証とmypy・pyrightの静的検査
Pythonでは役割が2つに分かれます。外から来たデータを検証するのがPydantic、コード中の分岐漏れを見つけるのがmypyやpyrightなどの型チェッカーです。
Pydantic 2.14.2のField(discriminator)による検証
Pydanticのunionsのドキュメントにあるとおり、Field(discriminator="kind") を付けると、判別プロパティで枝を決めてから検証します。
from typing import Annotated, Literal, Union
from pydantic import BaseModel, Field
class Circle(BaseModel):
kind: Literal["circle"]
radius: float
class Square(BaseModel):
kind: Literal["square"]
size: float
Shape = Annotated[Union[Circle, Square], Field(discriminator="kind")]
class Box(BaseModel):
shape: Shape
Box(shape={"kind": "triangle", "base": 1}) を実行すると、エラーは1件です(抜粋)。
1 validation error for Box
shape
Input tag 'triangle' found using 'kind' does not match any of the expected tags:
'circle', 'square' [type=union_tag_invalid, ...]
同じ入力を discriminator の無い Union[Circle, Square] に渡すと、4 validation errors になります(両方の枝の literal_error と missing)。{"kind": "circle", "radius": "x"} でも、判別ありは shape.circle.radius の1件、判別なしは3件でした。判別プロパティを持たせられない形なら、Discriminator に独自の関数を渡して判別値の取り出し方を決めることもできます。
mypy・pyrightとassert_neverによる網羅性検査
Pydanticは実行時の検証で、分岐の書き忘れは見つけません。コード側の網羅性は、Python 3.11で追加された typing.assert_never と型チェッカーで確かめます。
from dataclasses import dataclass
from typing import Literal, assert_never
@dataclass
class Circle:
radius: float
kind: Literal["circle"] = "circle"
@dataclass
class Square:
size: float
kind: Literal["square"] = "square"
@dataclass
class Triangle:
base: float
height: float
kind: Literal["triangle"] = "triangle"
Shape = Circle | Square | Triangle
def area(s: Shape) -> float:
if s.kind == "circle":
return 3.14159 * s.radius ** 2
elif s.kind == "square":
return s.size ** 2
else:
assert_never(s)
mypy 2.4.1(--strict)とpyright 1.1.414は、どちらも Triangle を名指しします。
mypy: error: Argument 1 to "assert_never" has incompatible type "Triangle"; expected "Never" [arg-type]
pyright: error: Argument of type "Triangle" cannot be assigned to parameter "arg" of type "Never"
TypeScriptの const exhaustive: never = shape; と同じ仕組みです。assert_never を置かず match 文で Circle と Square だけを書いた関数も、戻り値を float と宣言していればmypyが Missing return statement、pyrightが must return value on all code paths を出しますが、取りこぼしたクラス名は出ません。分岐の最後には assert_never を置いてください。
C#・F#・Rust・protobufでの判別可能なユニオン
同じ構造は他の言語やスキーマ定義にもあります。名称と、網羅漏れがどう報告されるかを実測で整理しました(2026年11月5日)。
| 言語・ツール | 相当する機能 | 網羅漏れの報告 | 重さ |
|---|---|---|---|
| TypeScript 7.0.2 | Discriminated Union | neverへの代入でTS2322 | エラー |
| Python(mypy 2.4.1・pyright 1.1.414) | Literalの判別 | assert_neverで報告 | エラー |
| Python(Pydantic 2.14.2) | discriminator | 報告しない(実行時に検証) | – |
| C# 15(.NET 11 RC3) | union宣言 | switch式でCS8509 | 警告 |
| F#(.NET 11 RC3のfsi) | 判別共用体 | matchでFS0025 | 警告 |
| Rust 1.99.1 | enum | matchでE0004 | エラー |
| Protocol Buffers | oneof | 生成コードの言語に依存 | – |
C# 15のunion宣言とF#の判別共用体
「Discriminated Union」はF#の言語機能の名前でもあり、Microsoft Learnの日本語版では「判別共用体」と訳されています。C#は abstract record と派生レコードで代用してきましたが、C# 15で union 宣言が入りました(Union types (C# reference))。C# 15を含む.NET 11は、2026年11月5日時点ではRC3で、正式版は11月10日の予定です。
public record Circle(double Radius);
public record Square(double Size);
public record Triangle(double Base, double Height);
public union Shape(Circle, Square, Triangle);
public static class Geo
{
public static double Area(Shape s) => s switch
{
Circle c => System.Math.PI * c.Radius * c.Radius,
Square q => q.Size * q.Size,
};
}
.NET SDK 11.0.100-rc.3(net11.0、LangVersion指定なし)でビルドすると、次の警告が出ます。日本語環境では「パターン ‘Triangle’ がカバーされていません」と訳されて表示されます。
warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern 'Triangle' is not covered.
Triangle のアームを足すとCS8509は消えます。注意点は3つです。1つ目は、これが警告でビルドは成功することです。<WarningsAsErrors>CS8509</WarningsAsErrors> をプロジェクトに入れると、同じ箇所が error CS8509 になってビルドが止まります。2つ目は、_ => 0 のような破棄アームを足すと Triangle が抜けていても警告が消えることです。3つ目は既定値で、フィールドや配列要素の初期値のunionは中身が null です。全ケースを書いた switch に new Shape[1] の要素を渡すと、警告なしでビルドが通り、実行時に SwitchExpressionException になります。リファレンスが破棄アームではなく null アームを勧めているのはこの2点のためで、null アームなら新しいケースを足したときの警告も残ります。値型のケースは object? に格納されボックス化される、ともリファレンスにあります。.NET 11全体の変更点は.NET 11の新機能とリリース日|サポート期限・C# 15・.NET 10との挙動差を実測【RC1】にまとめています。
F#の判別共用体は、ケースに名前とデータを持たせる形で書きます。
type Shape =
| Circle of radius: float
| Square of size: float
| Triangle of b: float * h: float
let area shape =
match shape with
| Circle r -> System.Math.PI * r * r
| Square s -> s * s
dotnet fsi で実行すると、warning FS0025: Incomplete pattern matches on this expression. For example, the value 'Triangle (_, _)' may indicate a case not covered by the pattern(s). が出たうえで、最後まで実行されます。F#側の最近の言語変更はF# 9の新機能まとめ|null許容参照型・#nowarnの変更とF# 10・F# 11での違いを実測で扱っています。
Rustのenumとprotobufのoneof
Rustのenumは、バリアントごとに違うデータを持てる点でDiscriminated Unionに当たります。判別プロパティを自分で用意する必要はなく、match の網羅性は言語仕様として強制されます。
enum Shape {
Circle { radius: f64 },
Square { size: f64 },
Triangle { base: f64, height: f64 },
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Square { size } => size * size,
}
}
rustc --edition 2021 でコンパイルすると、rustc 1.99.1 は error[E0004]: non-exhaustive patterns: `&Shape::Triangle { .. }` not covered を返してコンパイルを止めます。Rustでは網羅性の検査が言語仕様に組み込まれており、補助コードを書かなくても網羅漏れがエラーになります。TypeScriptとPythonは never や assert_never を置いた箇所で型エラーになり、C#とF#は既定では警告です。
Protocol Buffersの oneof もスキーマ上で同じ構造を表します。公式ガイドは「Oneof fields are like optional fields except all the fields in a oneof share memory, and at most one field can be set at the same time.」と定義し、A oneof cannot be repeated. と制約も明記しています。網羅性の検査は生成先の言語次第です。protoファイルの書き方はProtocol Buffersとは?protoファイルの書き方と採用判断を実装者向けに解説にまとめています。
よくある質問(FAQ)
Discriminated Unionと「タグ付きユニオン」「判別共用体」「代数的データ型」は同じものですか?
ほぼ同じ構造を指します。タグ付きユニオン(tagged union)は一般的な呼び名、Discriminated UnionはTypeScriptやF#での名称、判別共用体はその日本語訳です。代数的データ型(ADT)は直和型に加えて直積型(タプルやレコード)も含む、より広い概念です。
「discriminant union」「descriminated union」は別のものですか?
別の機能ではありません。discriminant(判別子)は判別に使うプロパティを指す語で、型の名前としてはTypeScriptのハンドブックもMicrosoft Learnも「discriminated union」を使っています。「descriminated」は綴りの誤りです。検索するときは「discriminated union」か「tagged union」で探すと公式資料に当たります。
判別プロパティの名前はkindとtypeのどちらにすべきですか?
どちらでも同じように動きます。公式ハンドブックの例は kind ですが、Reduxのアクションなど外部の慣習で type が決まっていればそれに合わせ、プロジェクト内で統一してください。
判別プロパティが2つ必要な場合はどうしますか?
判別用プロパティが2つあっても、許可する値の組み合わせごとにユニオンのメンバーを定義すれば絞り込みは働きます。避けたいのは、各プロパティを独立したユニオン型にして1つのオブジェクト型にまとめる書き方で、この形では意図しない組み合わせも通ります。組み合わせが増えすぎるなら、1段目の判別プロパティで大分類を絞り、その中に別の判別プロパティを持つユニオンを入れ子にします。
クラスの継承とDiscriminated Unionはどう使い分けますか?
振る舞い(メソッド)が型ごとに違い、呼び出し側は共通のインターフェースだけ知っていればよいなら継承やインターフェースが向きます。データの形だけが違い、処理は呼び出し側で分岐したい場合や、値がJSONとして往復する場合はDiscriminated Unionが向きます。JSONからはクラスのプロトタイプが復元されないため、APIの境界では判別プロパティで種類を明示するほうが扱いやすくなります。