Q8: What are Literal Types and how do `as const` assertions work?
Literal types restrict variables to exact concrete values (strings, numbers, or booleans) rather than wider primitive categories.
A const assertion (as const) instructs TypeScript to infer the narrowest possible literal types for object properties and arrays, turning properties into readonly fields.
as const Assertion
// Standard object inference
const config = {
endpoint: "/api",
retries: 3
}; // Type: { endpoint: string; retries: number; }
// const assertion
const constConfig = {
endpoint: "/api",
retries: 3
} as const; // Type: { readonly endpoint: "/api"; readonly retries: 3; }💡 as const prevents property widening and marks array/object members read-only.
Key Takeaways
- Literal types lock values to exact concrete constants.
as constcreates deeply immutable readonly literal data types.