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])
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
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Absent | JavaScript 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. |
| TypeScript | Native | TypeScript has string, number, boolean and enum literal types, unions of them, and as const. No example file exists. |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | Kotlin 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. |
| SQL | Idiom | A CHECK constraint with IN can limit a column to listed values. No example file exists. |
| Bash | Does not apply | Bash has no types. |
| PowerShell | Idiom | PowerShell uses .NET enums. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types. |
| CSS | Does not apply | CSS keywords are fixed values, but CSS has no type system for them. |
| Regular expressions | Does not apply | A 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.
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)
(<Status.OK: 0>,) (0, 1)
ok fail
False 3
2
- Verdict: stdlib.
typing.Literaltakes strings, numbers, booleans,Noneand enum members. A checker treatsStatusas the unionLiteral[Status.OK, Status.FAIL], so after the test forOKonlyFAILremains.Literal[True]andLiteral[1]are different types even thoughTrue == 1. Python does not check the annotation ofxwhen 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";
}
5 5 15
0 1
1
2 7
- Verdict: stdlib.
std::integral_constant<int, 5>is a type with one value, 5, andstd::true_typeis the same template withboolandtrue. Each such type is an empty class. Anenum classdoes not convert fromintwithout a cast, butstatic_castcan still make a value with no name.
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");
}
}
}
hi.... ....hi ..hi..
2
no constant CENTRE
- Verdict: idiom. Java has no literal types. An
enumclass has a fixed set of instances, so a parameter of typeAligntakes only these three, and aswitchexpression that leaves one out does not compile. A string from outside must go throughvalueOf, 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;
}
center 2
unknown 7
3
- Verdict: idiom. C has no literal types. An
enumgives names to integer constants, but the compiler lets anyintgo into anenumvariable, sonameneeds a fallback after theswitch. 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 }
Green 1
42 False
red
not a color
- Verdict: idiom. A C#
enumnames constants of an integer type, but a cast turns anyintinto aColor.(Color)42has no name, andEnum.IsDefinedreports that. Aswitchon 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))
}
Sunday Monday Tuesday
Weekday(9) false
Monday
- Verdict: idiom. Go has no literal types and no closed enums.
iotagives the constants 0, 1 and 2 of the named typeWeekday, but any integer of that type is allowed: the untyped constant 9 converts without a cast, and a conversion turns anyintinto aWeekday.
#[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>>());
}
Ok(Center) Err("bad align: centre")
Mod(2)
4
- Verdict: idiom. Rust has no literal types. An
enumwith 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>andMod<7>are different types, so the compiler rejects adding numbers with different moduli. The modulus costs no memory in each value.
Variations and related ideas
- 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 withkind: ShapeKind.Circlerejects an object whosekindisShapeKind.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 aLiteralString, but a plainstris not, so a query function that takes aLiteralStringrejects text from user input, which "could be vulnerable to an SQL injection attack"8. - Singleton objects. A Scala
objector a Kotlinobjectdeclaration 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 passingreq.methodwhere"GET" | "POST"is expected fails in TypeScript1. Useas 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)42is a validColorwith 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
- Everyday Types, The TypeScript Handbook, Literal Types; Literal Inference
- SIP-23, Literal-based singleton types, Scala Documentation, History; Introduction; Implementation status; Proposal summary
- PEP 586, Literal Types, Abstract; Shortening unions of literals; Interactions with enums and exhaustiveness checks; Related work
- Enums, The TypeScript Handbook, Union enums and enum member types
- The Java Language Specification, Java SE 25 Edition, Chapter 8, 8.9 Enum Classes
- Generic parameters, The Rust Reference, Const generics
- std::integral_constant, C++ reference, cppreference.com, Description
- typing, Python 3.14 documentation, typing.Literal
- Enumeration types, C# language reference, Introduction; Conversions
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 8JECRW Edit this page History Report an error Markdown