Programming Search⌘K

Conceptcore

Union type

Also called union, untagged union, C union, type union, union of types.

A union type has values that can be of any one of several types. A C union shares one block of memory between its members, and a TypeScript or Python union lists the allowed types.

Applies to
core-languages

Idea

Sometimes a value can have one of several types. An ID can be a number or a string. A setting can be a Boolean or a list of names. A union type says exactly that. Wikipedia says that "a union type specifies the permitted types that may be stored in its instances, e.g., float and int".1

def describe(value: int | str) -> str:
    if isinstance(value, int):
        return f"number {value}, doubled {value * 2}"
    return f"text {value}, upper {value.upper()}"


for v in [21, "ok"]:
    print(describe(v))
Output
number 21, doubled 42
text ok, upper OK

Before the code uses the value, it must find out which type the value has. Here isinstance does the check. After the check, the code can use the operations of that one type.

The name comes from sets: "If a type is considered as the set of all values that that type can take on, a union type is simply the mathematical union of its constituting types".1

How it works

The word union names two different things in programming.

A C union: shared memory. In C, "A union type describes an overlapping nonempty set of member objects".2 All members start at the same address. "The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time."2 The union itself does not record which member holds the value. The program must keep that information somewhere else. This is an untagged union.

A union of types: a set of allowed types. In TypeScript, "A union type is a type formed from two or more other types, representing values that may be any one of those types."3 Python writes the same idea as int | str.4 Here each value still knows its own type at run time, so the program can test the type with typeof or isinstance. The type checker uses the test to narrow the union to one member type. Before the test, "TypeScript will only allow an operation if it is valid for every member of the union".3

Tagged unions. A tagged union adds a tag that says which case is in use. Wikipedia describes a tagged union as "a data structure used to hold a value that could take on several different, but fixed, types", in which "a tag field explicitly indicates which type is in use".5 A C program builds one from a struct with an enum tag and a union. In TypeScript, a common field with literal types does the job: "When every type in a union contains a common property with literal types, TypeScript considers that to be a discriminated union".6 A tagged union is a sum type; see Sum types.

Untagged union (C) Union of types (TypeScript, Python) Tagged union (sum type)
Which case is in use the program must track it the run time type of the value a tag stored with the value
Check before use none; a wrong read is a bug typeof, isinstance, a type pattern a match or a switch on the tag
Storage the largest member a reference to the value the largest case plus the tag

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaIdiom
CNative
C#Native
JavaScriptIdiom
TypeScriptNative
GoIdiom
RustNative
KotlinIdiomKotlin has no union types; a sealed interface gives a closed set of cases, and a value of type Any can be tested with is in a when expression. No example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyEach column has one declared type.
BashDoes not applyEvery value in Bash is a string.
PowerShellIdiomA variable can hold a value of any type, and the -is operator tests the type; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no types.
CSSDoes not applyStyle rules have no types.
Regular expressionsDoes not applyA pattern has no types.

The example files take a value that is an integer or a string, find out which, and use it.

Language Verdict Form
Python native int | str, or typing.Union[int, str]74
JavaScript idiom any variable can hold any type; typeof tells them apart
TypeScript native number | string; discriminated unions with a common field36
Java idiom Object with type patterns, or a sealed interface
C native union, untagged2
C++ native union, untagged; std::variant as a tagged union89
C# native union types from C# 151011
Go idiom an interface type and a type switch; union terms only in type constraints12
Rust native union, untagged and unsafe to read; enum as a tagged union13
Kotlin idiom a sealed interface, or Any with when and is checks
PowerShell idiom any variable can hold any type; -is tells them apart
Bash n/a every value is a string
SQL n/a each column has one type
Regex n/a a pattern has no types
HTML/CSS n/a markup has no types

C++. A raw union has an active member, the one most recently written. cppreference warns: "It is undefined behavior to read from the member of the union that wasn't most recently written."8 std::variant is the safe form. "Any instance of variant at any given time either holds a value of one of its alternative types or holds no value."9

Rust. A Rust union has no active member: "every union access just interprets the storage as the type of the field used for the access".13 So every read of a union field must be in an unsafe block.13 Most Rust code uses an enum, which is a tagged union that the compiler checks.

C#. C# 15 added union types: "A union type represents a value that can be one of several case types."10 C# 15 is the default language version for projects that target .NET 11.11 The example file uses object and type patterns, which work in older versions too.

Go. An interface can list type terms such as int | string, but "Interfaces that are not basic may only be used as type constraints".12 So a variable cannot have such a type. A program uses any or another interface, and a type switch.

PythonGitHub
def describe(value: int | str) -> str:
    match value:
        case int(n):
            return f"number {n}, doubled {n * 2}"
        case str(s):
            return f"text {s}, upper {s.upper()}"


for v in [21, "ok"]:
    print(describe(v))
print("union object:", int | str)
Output
number 21, doubled 42
text ok, upper OK
union object: int | str
  • Verdict: native. int | str is a union type (Python 3.10 and later). Each value still carries its own type at run time.
  • A class pattern such as case int(n) tests the type and binds the value in one step.
  • The | on types builds a union object that isinstance also accepts.
#include <cctype>
#include <iostream>
#include <string>
#include <variant>

using IntOrText = std::variant<int, std::string>;

std::string describe(const IntOrText& value) {
    if (const int* n = std::get_if<int>(&value)) {
        return "number " + std::to_string(*n) + ", doubled " + std::to_string(*n * 2);
    }
    std::string s = std::get<std::string>(value);
    std::string upper = s;
    for (char& c : upper) {
        c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    }
    return "text " + s + ", upper " + upper;
}

int main() {
    for (const IntOrText& v : {IntOrText{21}, IntOrText{std::string("ok")}}) {
        std::cout << describe(v) << '\n';
    }
    IntOrText v = std::string("ok");
    try {
        std::cout << std::get<int>(v) << '\n';
    } catch (const std::bad_variant_access&) {
        std::cout << "wrong alternative: bad_variant_access\n";
    }
}
Output
number 21, doubled 42
text ok, upper OK
wrong alternative: bad_variant_access
  • Verdict: native. std::variant is a tagged union. It knows which alternative it holds, and std::get_if returns a null pointer for the wrong one.
  • std::get with the wrong alternative throws std::bad_variant_access, not undefined behavior.
  • A raw union also exists, but reading a member that was not written last is undefined behavior.
JavaGitHub
public class Main {
    static String describe(Object value) {
        return switch (value) {
            case Integer n -> "number " + n + ", doubled " + (n * 2);
            case String s -> "text " + s + ", upper " + s.toUpperCase();
            default -> throw new IllegalArgumentException("not a number or a string");
        };
    }

    public static void main(String[] args) {
        for (Object v : new Object[] {21, "ok"}) {
            System.out.println(describe(v));
        }
    }
}
Output
number 21, doubled 42
text ok, upper OK
  • Verdict: idiom. Java has no union types. The parameter has the type Object, and a switch with type patterns finds the actual type.
  • The compiler cannot know that only Integer and String arrive, so the switch needs a default branch.
  • A sealed interface with one record for each case gives a closed set that the compiler checks. That is a sum type.
#include <ctype.h>
#include <stdio.h>

enum kind { INT, TEXT };

struct int_or_text {
    enum kind kind; /* the tag: which member of the union holds the value */
    union {
        int i;
        const char *s;
    } as;
};

static void describe(struct int_or_text v) {
    switch (v.kind) {
    case INT:
        printf("number %d, doubled %d\n", v.as.i, v.as.i * 2);
        break;
    case TEXT:
        printf("text %s, upper ", v.as.s);
        for (const char *p = v.as.s; *p; p++) {
            putchar(toupper((unsigned char)*p));
        }
        putchar('\n');
        break;
    }
}

int main(void) {
    struct int_or_text values[] = {{.kind = INT, .as.i = 21}, {.kind = TEXT, .as.s = "ok"}};
    for (int i = 0; i < 2; i++) {
        describe(values[i]);
    }
    union {
        char c;
        double d;
    } u;
    printf("union size is the largest member: %s\n", sizeof u == sizeof(double) ? "yes" : "no");
    return 0;
}
Output
number 21, doubled 42
text ok, upper OK
union size is the largest member: yes
  • Verdict: native. A union stores one of its members at a time, all at the same address. It does not record which one.
  • The struct adds a kind field as the tag. Each write sets the tag, and each read checks it first.
  • The size of a union is the size of its largest member, plus any padding.
foreach (object v in new object[] { 21, "ok" })
{
    Console.WriteLine(Describe(v));
}

static string Describe(object value) => value switch
{
    int n => $"number {n}, doubled {n * 2}",
    string s => $"text {s}, upper {s.ToUpperInvariant()}",
    _ => throw new ArgumentException("not a number or a string"),
};
Output
number 21, doubled 42
text ok, upper OK
  • Verdict: native. C# 15 has union types, such as union Pet(Cat, Dog, Bird). This example uses object and type patterns, which work in older versions too.
  • A switch expression with type patterns tests the type and binds the value.
  • With object, the compiler cannot know the set of types, so the switch needs a _ branch.
JavaScriptGitHub
function describe(value) {
  if (typeof value === "number") {
    return `number ${value}, doubled ${value * 2}`;
  }
  if (typeof value === "string") {
    return `text ${value}, upper ${value.toUpperCase()}`;
  }
  throw new TypeError(`not a number or a string: ${typeof value}`);
}

for (const v of [21, "ok"]) {
  console.log(describe(v));
}
try {
  describe(true);
} catch (e) {
  console.log("error:", e.message);
}
Output
number 21, doubled 42
text ok, upper OK
error: not a number or a string: boolean
  • Verdict: idiom. JavaScript has no static types, so any variable can hold a value of any type. typeof tells them apart.
  • Nothing stops a caller from passing a third type, so the function checks for it and throws.
TypeScriptGitHub
function describe(value: number | string): string {
  if (typeof value === "number") {
    return `number ${value}, doubled ${value * 2}`;
  }
  return `text ${value}, upper ${value.toUpperCase()}`;
}

type Shape = { kind: "circle"; radius: number } | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.round(Math.PI * shape.radius ** 2);
    case "square":
      return shape.side ** 2;
  }
}

for (const v of [21, "ok"]) {
  console.log(describe(v));
}
console.log(`areas: ${area({ kind: "circle", radius: 2 })} ${area({ kind: "square", side: 3 })}`);
Output
number 21, doubled 42
text ok, upper OK
areas: 13 9
  • Verdict: native. number | string is a union type. Inside the if, typeof narrows value to number, and after it to string.
  • Shape is a discriminated union: the common field kind has a different literal type in each member, so a switch on it narrows the shape.
  • The types exist only at compile time. At run time the values are plain numbers, strings and objects.
package main

import (
	"fmt"
	"strings"
)

func describe(value any) string {
	switch v := value.(type) {
	case int:
		return fmt.Sprintf("number %d, doubled %d", v, v*2)
	case string:
		return fmt.Sprintf("text %s, upper %s", v, strings.ToUpper(v))
	default:
		return fmt.Sprintf("not a number or a string: %T", v)
	}
}

type intOrString interface {
	int | string
}

func double[T intOrString](x T) T {
	return x + x
}

func main() {
	for _, v := range []any{21, "ok"} {
		fmt.Println(describe(v))
	}
	fmt.Println("constraint:", double(21), double("ok"))
}
Output
number 21, doubled 42
text ok, upper OK
constraint: 42 okok
  • Verdict: idiom. A variable of type any holds a value of any type, and a type switch finds the actual type.
  • The interface intOrString lists the types int | string, but it can only be a type constraint, as in double. A variable cannot have that type.
  • + works in double because both int and string support it.
RustGitHub
enum IntOrText {
    Int(i64),
    Text(String),
}

fn describe(value: &IntOrText) -> String {
    match value {
        IntOrText::Int(n) => format!("number {}, doubled {}", n, n * 2),
        IntOrText::Text(s) => format!("text {}, upper {}", s, s.to_uppercase()),
    }
}

union Bits {
    float: f32,
    int: u32,
}

fn main() {
    for v in [IntOrText::Int(21), IntOrText::Text(String::from("ok"))] {
        println!("{}", describe(&v));
    }

    let b = Bits { float: 1.0 };
    let raw = unsafe { b.int };
    println!("bits of 1.0: {:#x}", raw);
}
Output
number 21, doubled 42
text ok, upper OK
bits of 1.0: 0x3f800000
  • Verdict: native. An enum with data is a tagged union, and match must handle every case.
  • A union is untagged. Reading a field reads the stored bits as that field's type, so it needs unsafe.
  • Here the read is valid, because every bit pattern is a valid u32. It shows the bits of the f32 value 1.0.
  • Sum types. A tagged union with a fixed set of cases that the compiler checks. See Sum types and Algebraic data type.
  • Enumerations. A tagged union whose cases carry no data. See Enumeration.
  • Optional values. T | None in Python and T | undefined in TypeScript are unions of a type with a type that has one value. See option-type.
  • Subtyping. Each member of a union is a subtype of the union, so a value of a member type can be used where the union is expected. See Subtyping.

Pitfalls

Reading the wrong member of an untagged union

A C union does not know which member holds the value. If the program reads a different member from the one it wrote, C reinterprets the bytes: "the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type".2 The result is a different value, not an error.

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

union number {
    int i;
    float f;
};

int main(void) {
    union number n;
    n.i = 42;
    printf("as int: %d, as float: %g\n", n.i, n.f);
    return 0;
}
Output
as int: 42, as float: 5.88545e-44

The fix is a tag: put the union in a struct with an enum field that records which member holds the value, and check it before each read. In C++, the same read is undefined behavior, so use std::variant.8

Overlapping member types

A type test checks whether the value is an instance of a type, and a value can belong to two member types at once. In Python, "bool is a subclass of int".7 So in a union int | bool, the test for int also matches True.

This code runs but gives a wrong answer on purpose.

def describe(value: int | bool) -> str:
    if isinstance(value, int):
        return "number"
    return "flag"


print(describe(True))
Output
number

The fix is to test the narrower type first: if isinstance(value, bool). A tagged union does not have this problem, because the tag names the case.

A union without a check

Code that uses a union value without a check fails at run time in a dynamic language and does not compile in TypeScript. In C, it compiles and reads the wrong bytes. Each use of a union value needs a check, so a union that many functions pass around spreads checks through the code. A sum type with a match in one place, or a method on each case, keeps the checks together.

Cost

A C union takes the size of its largest member, plus any padding. It has no tag, so it needs no extra space, but the program must store the tag somewhere else. A tagged union adds the tag, often one byte or one word. A union of types in a dynamic language costs nothing extra in the value, because each value already carries its type; the check costs one type test. std::variant stores the largest alternative plus an index.

History

Wikipedia lists ALGOL 68 among the early languages with unions: "ALGOL 68 has tagged unions, and uses a case clause to distinguish and extract the constituent type at runtime."1 COBOL can lay a second data item over the same memory.1 C has untagged unions. Wikipedia notes that "untagged unions are generally only provided in untyped languages or in a type-unsafe way (as in C)".1 Later typed languages added safe forms: std::variant in C++, union types in TypeScript, the X | Y syntax in Python 3.10, and union types in C# 15.93410

References

  1. Union type, Wikipedia, the introduction; Untagged unions; Unions in various programming languages
  2. ISO/IEC 9899:201x, committee draft N1570 (C11), 6.2.5p20; 6.7.2.1p16; 6.5.2.3 footnote 95
  3. TypeScript Handbook, Everyday Types, Union Types; Working with Union Types
  4. PEP 604: Allow writing union types as X | Y, the header (Python-Version 3.10); Abstract
  5. Tagged union, Wikipedia, the introduction
  6. TypeScript Handbook, Narrowing, Discriminated unions
  7. The Python Standard Library, Built-in Types, Union Type; Boolean Type
  8. cppreference.com, Union declaration, Explanation (the active member)
  9. Working Draft, Standard for Programming Language C++ (N4950), [variant.variant.general], 22.6.3.1 General
  10. C# language reference, Union types, the introduction
  11. What's new in C# 15, the introduction; Union types
  12. The Go Programming Language Specification, Interface types, General interfaces
  13. The Rust Reference, Unions, Reading and writing union fields

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/N42S89/text.yaml