Union Types
Whether 'or' lives in the type or in the branches — PHP 8.0 union types against the type-system expressiveness of 10 languages.
C C23
#include <stdio.h>
#include <string.h>
/* C has no type-level union: a "tagged union" pairs a tag with a raw union
and every access is guarded by hand */
typedef struct {
enum { T_INT, T_STR } tag;
union {
int i;
char s[16];
} as;
} Value;
static void show(Value v) {
if (v.tag == T_INT) printf("int %d\n", v.as.i);
else printf("str %s\n", v.as.s);
}
int main(void) {
Value a; a.tag = T_INT; a.as.i = 7;
Value b; b.tag = T_STR; strcpy(b.as.s, "hey");
show(a);
show(b);
return 0;
}
int 7 str hey
C++ C++26
#include <cstdio>
#include <string>
#include <variant>
// std::variant (C++17) is a type-safe union: the compiler tracks which
// alternative is active, and wrong access throws
using Value = std::variant<int, std::string>;
static void show(const Value &v) {
if (auto *i = std::get_if<int>(&v)) {
std::printf("int %d\n", *i);
} else {
std::printf("str %s\n", std::get<std::string>(v).c_str());
}
}
int main() {
show(7);
show(std::string("hey"));
return 0;
}
int 7 str hey
C# v11.0.100
// C# has no union type; the idiom is a documented contract over a common
// supertype plus runtime pattern matching
var r1 = Show(7);
var r2 = Show("hey");
var r3 = "";
try { Show(1.5); }
catch (ArgumentException e) { r3 = $"ArgumentException: {e.Message}"; }
static string Show(object v) => v switch
{
int i => $"int {i}",
string s => $"str {s}",
_ => throw new ArgumentException("unsupported"),
};
Console.WriteLine(r1);
Console.WriteLine(r2);
Console.WriteLine(r3);
int 7 str hey ArgumentException: unsupported
Go v1.27.4
package main
import "fmt"
// Go has no union type; interface{} plus a type switch is the idiom
func show(v any) string {
switch t := v.(type) {
case int:
return fmt.Sprintf("int %d", t)
case string:
return fmt.Sprintf("str %s", t)
default:
return fmt.Sprintf("unsupported %T", t)
}
}
func main() {
fmt.Println(show(7))
fmt.Println(show("hey"))
fmt.Println(show(1.5))
}
int 7 str hey unsupported float64
Java v27.0.1
public class Main {
// sealed hierarchy: the type system lists the allowed alternatives
sealed interface Value permits IntV, StrV {}
record IntV(int i) implements Value {}
record StrV(String s) implements Value {}
static String show(Value v) {
// pattern switch is exhaustive over the sealed family
return switch (v) {
case IntV x -> "int " + x.i();
case StrV x -> "str " + x.s();
};
}
public static void main(String[] args) {
System.out.println(show(new IntV(7)));
System.out.println(show(new StrV("hey")));
}
}
int 7 str hey
JavaScript v26.13.1
// JS has no type layer: branches run on the live value
function show(v) {
if (typeof v === "number") return "number " + v;
if (typeof v === "string") return "string " + v;
return "unsupported " + typeof v;
}
console.log(show(7));
console.log(show("hey"));
console.log(show({}));
number 7 string hey unsupported object
PHP v8.6.0
// union type: the parameter accepts int OR string
function parse(int|string $v): int|string {
return is_int($v) ? (string)($v * 2) : strtoupper($v);
}
echo parse(21), "\n";
echo parse("abc"), "\n";
// runtime check: an array matches neither arm -> TypeError
try {
parse([]);
} catch (TypeError $e) {
// trim the location suffix so the message stays environment-independent
echo "TypeError: ", strstr($e->getMessage(), ", called in", true), "\n";
}
// ?T is sugar for T|null, itself a union
function greet(?string $name): string {
return $name === null ? "hi, guest" : "hi, $name";
}
echo greet(null), "\n";
echo greet("ada"), "\n";
42 ABC TypeError: parse(): Argument #1 ($v) must be of type string|int, array given hi, guest hi, ada
Python v3.15.2
# PEP 604 union syntax in annotations; the runtime accepts anything unless
# you check yourself
def show(v: int | str) -> str:
if not isinstance(v, (int, str)):
raise TypeError(f"expected int | str, got {type(v).__name__}")
if isinstance(v, int):
return f"int {v * 2}"
return f"str {v.upper()}"
print(show(7))
print(show("hey"))
print("annotation:", show.__annotations__["v"])
try:
print(show(1.5))
except TypeError as e:
print("TypeError:", e)
int 14 str HEY annotation: int | str TypeError: expected int | str, got float
Rust v1.99.1
// the enum IS the union: each variant carries its own data, and match
// must be exhaustive at compile time
enum Value {
Int(i32),
Str(String),
}
fn show(v: Value) -> String {
match v {
Value::Int(i) => format!("int {}", i),
Value::Str(s) => format!("str {}", s),
}
}
fn main() {
println!("{}", show(Value::Int(7)));
println!("{}", show(Value::Str("hey".to_string())));
}
int 7 str hey
TypeScript v26.13.1
// TS union types are compile-time only: the type layer vanishes in the output
function show(v: number | string): string {
if (typeof v === "number") return "number " + v;
return "string " + v;
}
console.log(show(7));
console.log(show("hey"));
// show(true); // compile error: Argument of type 'boolean' is not assignable
number 7 string hey
Language differences
C: no type-level union (example): the idiom is a tagged union — a tag enum paired with a raw union, every access hand-guarded; C's union is a memory-layout construct, not a type-system concept.
C++: std::variant (C++17, example): a type-safe union where get_if probes losslessly and get throws bad_variant_access on the wrong arm; the compiler knows the active alternative — the closest thing to a real union type in the C family.
C#: no built-in union type (example): the idiom is a common supertype object plus switch pattern matching and throwing on the miss; libraries like OneOf or abstraction layers simulate it, and the official type system has no 'or' operator.
Go: no union type (example): any (interface{}) plus a type switch is the official substitute; exhaustiveness is left to a default arm, with no declarable 'or' at the type level.
Java: no native union (example): a sealed interface plus records (17+) enumerates every allowed subtype and a pattern switch (21+) is compile-exhaustive — semantically the equivalent of a data-carrying union, with exhaustiveness compiler-enforced.
JavaScript: no type layer (example): branches run on the live value and typeof narrowing is a runtime fact; the type-level union only exists in JSDoc/TS.
PHP: 8.0+ union types (example): int|string goes into parameters/returns/properties and is enforced at runtime — legal values pass, an out-of-family value throws TypeError; ?T is sugar for T|null; 8.1 added intersections, 8.2 DNF, and 8.3 typed class constants.
Python: 3.10+ PEP 604 annotations, int | str (example): annotations are runtime-reflectable (__annotations__), but the engine enforces nothing — an out-of-family value slips through silently unless you isinstance-check by hand (or lean on Pydantic-style libraries).
Rust: the enum IS the data-carrying union (example): variants can hold data and match is compile-exhaustive; a runtime union does not exist — the compiler has already enumerated every branch.
TypeScript: native unions, number | string (example): full compile-time expressiveness (discriminated unions, narrowing), but the type layer is erased in the output — at runtime, same as JS, typeof branches do the work.