Programming Search⌘K

Conceptadvanced

Literal and singleton types

Also called literal type, singleton type, literal types, singleton types, Literal, typing.Literal, string literal type, numeric literal type, boolean literal type, union of literals, as const, integral_constant.

A literal type, or singleton type, has one value, such as "left" or 42. A union of literal types lists the values that a variable may hold, and the checker rejects any other value.

Applies to
core-languages

Idea

Many parameters take only a few values: an alignment is "left", "right" or "center", and a comparison returns -1, 0 or 1. A type such as string or int allows every other value too, so a misspelled "centre" passes the type check and fails later. A literal type has one value, the literal itself. A union of literal types lists the exact values that are allowed, so a checker can reject "centre" before the program runs. Python spells this Literal["left", "right", "center"]. A type checker reads the annotation, and the program can also read the values when it runs.

from typing import Literal, get_args

Align = Literal["left", "right", "center"]


def pad(text: str, width: int, align: Align) -> str:
    match align:
        case "left":
            return text.ljust(width, ".")
        case "right":
            return text.rjust(width, ".")
        case "center":
            return text.center(width, ".")


print(pad("hi", 6, "left"), pad("hi", 6, "right"), pad("hi", 6, "center"))
print(get_args(Align))

# pad("hi", 6, "centre")  # a type checker rejects this argument
user_input = "centre"
print(user_input in get_args(Align))
print(Literal["a", "b"] == Literal["b", "a"], Literal[1, Literal[2]] == Literal[1, 2])
Output
hi.... ....hi ..hi..
('left', 'right', 'center')
False
True True

Align allows three strings and no others. A type checker such as mypy rejects the call with "centre", and it knows that the match covers every case, so the function always returns a string. Python does not check the annotation when the program runs, so a value that comes from outside, such as user input, must be tested against get_args(Align). The last line shows that a Literal with several values acts as a set: the order does not matter, and nested literals flatten.

How it works

A value in a type position. In TypeScript, "In addition to the general types string and number, we can refer to specific strings and numbers in type positions"1. In Scala, a literal can "appear in type position, designating the corresponding singleton type"2, so val one: 1 = 1 declares a value whose type is 12. In Python, "Literal types indicate that some expression has literally a specific value"3. A literal type is a subtype of the type of its value: the type "left" is a subtype of string.

Singleton types. Scala describes "Singleton types, types which have a unique inhabitant"2, and says that "by pairing a type with its unique inhabitant, singleton types bridge the gap between types and values"2. A literal type is a singleton type whose value is a literal. In Scala, the type of an object definition is also a singleton type2. The unit type is a singleton type too, but it has one value in total, while a language with literal types has a singleton type for each literal.

Unions of literals. One literal type alone is of little use, "But by combining literals into unions, you can express a much more useful concept - for example, functions that only accept a certain set of known values"1. In Python, a Literal with several values "is equivalent to Union[Literal[v1], Literal[v2], Literal[v3]]"3 for Literal[v1, v2, v3]. In TypeScript, "The type boolean itself is actually just an alias for the union true | false"1. See union type.

Inference and widening. A checker must decide when to give a literal its own type and when to widen it to the general type. In TypeScript, a const string "can only represent 1 possible string"1, so it gets a literal type, but a property of an object can change, so "obj.counter must have the type number, not 0, because types are used to determine both reading and writing behavior"1. "The as const suffix acts like const but for the type system, ensuring that all properties are assigned the literal type instead of a more general version like string"1.

Enums as unions of literals. An enumeration lists a fixed set of named values, so a checker can treat it as a union of one type for each member. In TypeScript, when all members have literal values, "enum members also become types as well!"4, and "enum types themselves effectively become a union of each enum member"4. PEP 586 makes the same move for Python: a checker can "treat them as being approximately equivalent to the union of their values"3, so that the code for unions gives exhaustive checks on enums too. Java has no literal types, but an enum class is "a restricted kind of class that defines a small set of named class instances"5. See enumeration.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaIdiom
CIdiom
C#Idiom
JavaScriptAbsentJavaScript has no static types. A program can keep allowed values in a frozen object and test a value when it runs. No example file exists.
TypeScriptNativeTypeScript has string, number, boolean and enum literal types, unions of them, and as const. No example file exists.
GoIdiom
RustIdiom
KotlinIdiomKotlin has enum classes for a fixed set of values, and an object declaration has one instance. No example file exists because kotlinc is not installed.
SQLIdiomA CHECK constraint with IN can limit a column to listed values. No example file exists.
BashDoes not applyBash has no types.
PowerShellIdiomPowerShell uses .NET enums. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no types.
CSSDoes not applyCSS keywords are fixed values, but CSS has no type system for them.
Regular expressionsDoes not applyA regular expression has no types.
Language Verdict Mechanism
Python stdlib typing.Literal, checked by a static type checker; enum.Enum for named sets
JavaScript absent no static types; a frozen object of constants and a test when the program runs
TypeScript native string, number, boolean and enum literal types; unions of them; as const
Java idiom an enum class lists a fixed set of instances; switch can check that it covers them
Kotlin idiom enum class for a fixed set; an object declaration has exactly one instance
C# idiom enum names constants of an integer type, but any value of that type converts to it
Go idiom a named integer type with constants from iota; any value of the type is allowed
Rust idiom an enum with unit variants; const generics put a constant value in a type
C idiom enum names int constants; the compiler does not limit a variable to them
C++ stdlib std::integral_constant is a type for one value; enum class for named sets
Bash n/a Bash has no types
PowerShell idiom .NET enums, as in C#
SQL idiom a CHECK constraint with IN limits a column to listed values
Regex n/a a pattern has no types
HTML n/a HTML has no types
CSS n/a CSS keywords are fixed values, but CSS has no type system for them

TypeScript and Scala have literal types in the language, and Python adds them through typing for static checkers. Java, C#, Kotlin, Go, Rust and C get a closed set of values from an enumeration, which is a separate type, not a union of literals. C++ can make a type for one constant with a template.

The example files show these differences. Python shows Literal with enum members and with Final. Java shows an enum and a switch that must cover every constant. C# shows that a cast can put a value outside the enum into an enum variable. Go shows that a constant outside the set still has the named type. Rust shows an enum and a const generic parameter that makes Mod<5> and Mod<7> different types. C shows that an enum variable accepts any int. C++ shows std::integral_constant and std::true_type.

PythonGitHub
from enum import Enum
from typing import Final, Literal, get_args


class Status(Enum):
    OK = 0
    FAIL = 1


Done = Literal[Status.OK]  # a type with one value
Bit = Literal[0, 1]
MAX: Final = 3  # a checker gives MAX the type Literal[3]


def label(s: Status) -> str:
    if s is Status.OK:
        return "ok"
    # Here a checker narrows s to Literal[Status.FAIL].
    return "fail"


print(get_args(Done), get_args(Bit))
print(label(Status.OK), label(Status.FAIL))
print(Literal[True] == Literal[1], MAX)
x: Bit = 2  # a checker rejects this, but Python runs it
print(x)
Output
(<Status.OK: 0>,) (0, 1)
ok fail
False 3
2
  • Verdict: stdlib. typing.Literal takes strings, numbers, booleans, None and enum members. A checker treats Status as the union Literal[Status.OK, Status.FAIL], so after the test for OK only FAIL remains. Literal[True] and Literal[1] are different types even though True == 1. Python does not check the annotation of x when it runs.
#include <iostream>
#include <type_traits>

using Five = std::integral_constant<int, 5>;

template <int N>
int times(Five) {
    return N * Five::value; // Five has one value, known at compile time
}

enum class Align { Left, Right, Center };

int main() {
    std::cout << Five::value << " " << Five{}() << " " << times<3>(Five{}) << "\n";
    std::cout << std::is_same_v<Five, std::integral_constant<int, 6>> << " "
              << std::is_same_v<std::true_type, std::integral_constant<bool, true>> << "\n";
    std::cout << sizeof(Five) << "\n";

    Align a = Align::Center;
    // Align b = 2; // error: no conversion from int to Align
    Align c = static_cast<Align>(7); // an explicit cast still works
    std::cout << static_cast<int>(a) << " " << static_cast<int>(c) << "\n";
}
Output
5 5 15
0 1
1
2 7
  • Verdict: stdlib. std::integral_constant<int, 5> is a type with one value, 5, and std::true_type is the same template with bool and true. Each such type is an empty class. An enum class does not convert from int without a cast, but static_cast can still make a value with no name.
JavaGitHub
public class Main {
    enum Align { LEFT, RIGHT, CENTER }

    static String pad(String text, int width, Align align) {
        int space = width - text.length();
        // A switch expression on an enum must cover every constant.
        return switch (align) {
            case LEFT -> text + ".".repeat(space);
            case RIGHT -> ".".repeat(space) + text;
            case CENTER -> ".".repeat(space / 2) + text + ".".repeat(space - space / 2);
        };
    }

    public static void main(String[] args) {
        for (Align a : Align.values()) {
            System.out.print(pad("hi", 6, a) + " ");
        }
        System.out.println();
        System.out.println(Align.valueOf("CENTER").ordinal());
        try {
            Align.valueOf("CENTRE");
        } catch (IllegalArgumentException e) {
            System.out.println("no constant CENTRE");
        }
    }
}
Output
hi.... ....hi ..hi.. 
2
no constant CENTRE
  • Verdict: idiom. Java has no literal types. An enum class has a fixed set of instances, so a parameter of type Align takes only these three, and a switch expression that leaves one out does not compile. A string from outside must go through valueOf, which throws for a name that is not a constant.
#include <stdio.h>

enum align { ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTER };

static const char *name(enum align a) {
    switch (a) {
    case ALIGN_LEFT:
        return "left";
    case ALIGN_RIGHT:
        return "right";
    case ALIGN_CENTER:
        return "center";
    }
    return "unknown";
}

int main(void) {
    enum align a = ALIGN_CENTER;
    printf("%s %d\n", name(a), a);

    enum align b = 7; /* accepted: an enum converts from int */
    printf("%s %d\n", name(b), b);

    int sum = ALIGN_RIGHT + ALIGN_CENTER; /* enum constants are ints */
    printf("%d\n", sum);
    return 0;
}
Output
center 2
unknown 7
3
  • Verdict: idiom. C has no literal types. An enum gives names to integer constants, but the compiler lets any int go into an enum variable, so name needs a fallback after the switch. Enum constants take part in arithmetic like any other integer.
using System;

Color c = Color.Green;
Console.WriteLine($"{c} {(int)c}");

Color odd = (Color)42; // compiles: any int converts to Color
Console.WriteLine($"{odd} {Enum.IsDefined(odd)}");

Console.WriteLine(Describe(Color.Red));
Console.WriteLine(Describe(odd));

static string Describe(Color c) => c switch
{
    Color.Red => "red",
    Color.Green => "green",
    Color.Blue => "blue",
    _ => "not a color", // needed: Color can hold other values
};

enum Color { Red, Green, Blue }
Output
Green 1
42 False
red
not a color
  • Verdict: idiom. A C# enum names constants of an integer type, but a cast turns any int into a Color. (Color)42 has no name, and Enum.IsDefined reports that. A switch on an enum needs a default arm, because the compiler cannot assume that the value is one of the names.
package main

import "fmt"

type Weekday int

const (
	Sunday Weekday = iota
	Monday
	Tuesday
)

func (d Weekday) String() string {
	switch d {
	case Sunday:
		return "Sunday"
	case Monday:
		return "Monday"
	case Tuesday:
		return "Tuesday"
	}
	return fmt.Sprintf("Weekday(%d)", int(d))
}

func main() {
	fmt.Println(Sunday, Monday, Tuesday)
	var d Weekday = 9 // an untyped constant converts without a cast
	fmt.Println(d, d == Tuesday)
	n := 1
	fmt.Println(Weekday(n))
}
Output
Sunday Monday Tuesday
Weekday(9) false
Monday
  • Verdict: idiom. Go has no literal types and no closed enums. iota gives the constants 0, 1 and 2 of the named type Weekday, but any integer of that type is allowed: the untyped constant 9 converts without a cast, and a conversion turns any int into a Weekday.
RustGitHub
#[derive(Debug, Clone, Copy, PartialEq)]
enum Align {
    Left,
    Right,
    Center,
}

impl std::str::FromStr for Align {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "left" => Ok(Align::Left),
            "right" => Ok(Align::Right),
            "center" => Ok(Align::Center),
            _ => Err(format!("bad align: {s}")),
        }
    }
}

// The modulus is part of the type, so Mod<5> and Mod<7> are different types.
#[derive(Debug, Clone, Copy)]
struct Mod<const N: u32>(u32);

impl<const N: u32> Mod<N> {
    fn add(self, other: Mod<N>) -> Mod<N> {
        Mod((self.0 + other.0) % N)
    }
}

fn main() {
    println!("{:?} {:?}", "center".parse::<Align>(), "centre".parse::<Align>());
    let a: Mod<5> = Mod(3);
    let b: Mod<5> = Mod(4);
    println!("{:?}", a.add(b));
    // let c: Mod<7> = Mod(1); a.add(c); // error: expected Mod<5>, found Mod<7>
    println!("{}", std::mem::size_of::<Mod<5>>());
}
Output
Ok(Center) Err("bad align: centre")
Mod(2)
4
  • Verdict: idiom. Rust has no literal types. An enum with unit variants is a closed set, and code that reads text must parse it into a variant. A const generic parameter puts a value in a type: Mod<5> and Mod<7> are different types, so the compiler rejects adding numbers with different moduli. The modulus costs no memory in each value.
  • Discriminated unions. A literal-typed field, such as kind: "circle", tells a checker which case of a union a value belongs to. In the TypeScript enum example, an interface with kind: ShapeKind.Circle rejects an object whose kind is ShapeKind.Square4. See sum types.
  • Values as type arguments. C++ templates and Rust const generics take a constant as an argument to a type. "Const generic parameters allow items to be generic over constant values"6, so [u8; 4] and [u8; 8] are different types. "std::integral_constant wraps a static constant of specified type. It is the base class for the C++ type traits"7. Full dependent types go further and let a type depend on a value computed at run time.
  • Literal strings. Python has LiteralString, a "Special type that includes only literal strings"8. A string built from other literal strings is also a LiteralString, but a plain str is not, so a query function that takes a LiteralString rejects text from user input, which "could be vulnerable to an SQL injection attack"8.
  • Singleton objects. A Scala object or a Kotlin object declaration has a type with one instance. This is the singleton pattern built into the language, and in Scala the type of the object is a singleton type2.

Pitfalls

  • Widening loses the literal. A string in a mutable object widens to string, so passing req.method where "GET" | "POST" is expected fails in TypeScript1. Use as const, or annotate the object.
  • An enum is not a closed set in C#, C and Go. In C#, "explicit conversions exist between the enumeration type and its underlying integral type"9, so (Color)42 is a valid Color with no name. The C# documentation advises: "Use Enum.IsDefined to validate enum values when converting from numeric types"9. In Go, iota "represents successive untyped integer constants"10, and any other integer of the named type is allowed too. The C#, C and Go examples show this.
  • No check when the program runs. Python and TypeScript do not check literal types when the program runs. A value from a file, a form or the network must be tested against the allowed values, as the Python idea block does with get_args.

Cost

Literal types cost nothing when the program runs in TypeScript and Python, because the checker removes them. An enumeration in Java is a class with one object for each constant, and in C#, C and Go it is an integer5910. In C++ and Rust, the constant in a type such as std::integral_constant<int, 42> or [u8; 4] is known when the program compiles76.

History

Scala's type system had singleton types for paths from its earliest published work, and SIP-23 proposed literal types in 20142. Literal types were implemented in Typelevel Scala and in Dotty2. TypeScript has string, number and boolean literal types1. PEP 586, created in March 2019 for Python 3.8, added typing.Literal, and its authors wrote that its design ended up "converging into something similar to how literal types are handled in TypeScript"3.

References

  1. Everyday Types, The TypeScript Handbook, Literal Types; Literal Inference
  2. SIP-23, Literal-based singleton types, Scala Documentation, History; Introduction; Implementation status; Proposal summary
  3. PEP 586, Literal Types, Abstract; Shortening unions of literals; Interactions with enums and exhaustiveness checks; Related work
  4. Enums, The TypeScript Handbook, Union enums and enum member types
  5. The Java Language Specification, Java SE 25 Edition, Chapter 8, 8.9 Enum Classes
  6. Generic parameters, The Rust Reference, Const generics
  7. std::integral_constant, C++ reference, cppreference.com, Description
  8. typing, Python 3.14 documentation, typing.Literal
  9. Enumeration types, C# language reference, Introduction; Conversions
  10. The Go Programming Language Specification, Constants; Iota

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/8JECRW/text.yaml