literal type
A type that allows exactly one value, such as the string "GET", the number 404 or true.
In more detail
On their own they are rarely useful, but a union of literals such as "GET" | "POST" lists every valid value and rejects typos at compile time. const variables get literal types automatically; object properties need as const or a const type parameter to keep them.
Example
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";Related terms
- union type — A type that allows one of several listed types or values, written with a vertical bar, such as int | None in Python or "small" | "large" in TypeScript.
- as const — The TypeScript suffix as const, which tells the compiler to treat an object's values as fixed literal values rather than general types.
- type widening — The compiler giving a value a broader type than its exact value, such as string instead of "production", because it might change later.
- const type parameter — A type parameter marked const, such as <const T>, which makes the compiler infer the exact literal types of arguments, as if the caller wrote as const.
Taught in
- Why TypeScript: Contracts, Erased Types And Soundness — Production TypeScript
- Type Annotations, Type Inference And Contextual Typing — Production TypeScript
- Verify Your Environment: Running tsc And Bun TypeScript — Production TypeScript
- Primitive Types: String, Number, Boolean, Bigint And Symbol — Production TypeScript
- Literal Types: String, Number, Boolean Literals And const — Production TypeScript
- never: The Bottom Type And Exhaustive Switch Checking — Production TypeScript
- Discriminated Unions: Tagged Variants And Pattern Matching — Production TypeScript
- Typeof Guards, Truthiness And Equality Narrowing — Production TypeScript
- Const Type Parameters: Retaining Literal Types In Functions — Production TypeScript
- Conditional Types: Ternary Types And Type Inference With infer — Production TypeScript
- Mapped Types, Key Remapping With as And Template Literals — Production TypeScript
- The satisfies Operator: Safe Validation Without Widening — Production TypeScript
- The Spine Artifact: Generating Typed Models From OpenAPI — Production TypeScript