Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A const declaration in TypeScript defines a block-scoped variable with a constant reference to a value. Once initialized, the identifier cannot be reassigned to a new memory location. However, const enforces binding immutability, not value immutability; the internal properties of objects and arrays assigned to a const variable remain mutable at runtime.

Syntax and Initialization

A const variable must be initialized at the exact moment of its declaration. It cannot be declared and assigned later.
const MAX_RETRIES: number = 3; // Valid

const TIMEOUT: number; 
// TS Error: 'const' declarations must be initialized.

TypeScript Type Inference (Literal Types)

While JavaScript treats const purely as a runtime constraint, the TypeScript compiler uses const to alter type inference. When a primitive value is assigned to a const variable, TypeScript infers a literal type rather than widening it to a general primitive type.
let mutableStatus = "active"; 
// Inferred type: string (Type Widening)

const immutableStatus = "active"; 
// Inferred type: "active" (Literal Type)

Scope and Temporal Dead Zone (TDZ)

Like let, const is block-scoped, meaning it only exists within the nearest enclosing {} block. It is also subject to the Temporal Dead Zone (TDZ), meaning the variable cannot be accessed before its line of declaration is executed.
{
  // console.log(API_URL); // ReferenceError: Cannot access 'API_URL' before initialization
  const API_URL = "https://api.example.com";
}
// console.log(API_URL); // ReferenceError: API_URL is not defined (out of scope)

Reference vs. Value Immutability

Reassigning the identifier throws a compiler error, but mutating the properties of a complex data structure (like an object or array) is perfectly valid.
const config = { port: 8080, env: "dev" };

config.port = 9000; // Valid: Mutating the underlying object
config.env = "prod"; // Valid

config = { port: 3000, env: "test" }; 
// TS Error: Cannot assign to 'config' because it is a constant.

Const Assertions (as const)

To enforce deep immutability at the type level and prevent type widening for objects and arrays, TypeScript provides the as const assertion. This casts all properties to readonly and infers the narrowest possible literal types.
const strictConfig = { 
  port: 8080, 
  env: "dev" 
} as const;

// Inferred type:
// {
//   readonly port: 8080;
//   readonly env: "dev";
// }

strictConfig.port = 9000; 
// TS Error: Cannot assign to 'port' because it is a read-only property.
Master TypeScript with Deep Grasping Methodology!Learn More