TypeScript Fundamentals
Literal Types & const Assertions
Master string, number, and boolean literal types, union literals, and deep immutability using 'as const' assertions in TypeScript.
In TypeScript, Literal Types allow variables to be restricted to an exact, specific value (e.g., exact string "GET", number 404, or boolean true), rather than broader primitive types like string or number.
Combining literal types with as const assertions enables deep immutability and literal inference for objects and arrays.
1. String, Number, and Boolean Literal Types
Number and Boolean Literals
2. Type Widening & const Declarations
TypeScript infers literal types when variables are declared with const, but widens types to general primitives when declared with let:
3. as const Assertions (Const Assertions)
Adding as const to an object or array literal triggers Const Assertion rules:
1. Primitives inside the object/array are inferred as exact literal types (no widening).
2. Object properties become readonly.
3. Array literals become readonly tuples.
Standard Object vs as const Object
4. Converting as const Objects into Union Types
A common TypeScript design pattern is extracting union types dynamically from as const dictionary objects using keyof and indexed access types (typeof obj[keyof typeof obj]):
5. Interactive Code Playground
Test as const assertions and literal types below:
6. Common Pitfalls & Edge Cases
string.7. Summary Comparison Table
| Concept | Syntax | Inferred Behavior | |
|---|---|---|---|
| Literal Type | type Direction = "NORTH" \ | "SOUTH" | Restricts variable to exact values |
const Variable | const x = "hello" | Inferred as literal type "hello" | |
let Variable | let x = "hello" | Inferred as primitive string | |
as const Object | { key: "val" } as const | Readonly object with literal property types |
as const Array | [1, 2, 3] as const | Readonly tuple readonly [1, 2, 3] |