- Abstract class
- Annotations
- Array
- Asserts
- Class
- Const
- Decorators
- Default parameter
- Dictionary
- Enum
- For loop
- forEach()
- Function
- Generics
- Index signature
- Infer
- Inheritance
- Interface
- Let
- Map type
- Mixin
- Module
- Namespace
- Never
- Object type
- Operator
- Optional parameter
- Promise
- Property
- Tuples
- Type alias
- Type guard
- Type narrowing
- Union
- Utility types
- Var
- Void
TYPESCRIPT
TypeScript Const: Syntax, Usage, and Examples
The const
keyword in TypeScript declares variables that you can’t reassign. While the variable itself stays constant, the value it holds—if it's an object or array—can still be modified. TypeScript const declarations offer immutability at the binding level, not deep immutability of the value.
How to Use TypeScript Const
The basic syntax for a const TypeScript declaration is simple:
const name = "Alice";
This creates a constant binding for the variable name
. You cannot reassign name
later:
name = "Bob"; // Error: Cannot assign to 'name' because it is a constant.
However, if name
refers to an object or array, you can still change its internal structure:
const user = { age: 30 };
user.age = 31; // This is allowed.
The const in TypeScript freezes the reference, not the data inside the reference.
When to Use Const in TypeScript
You should use const TypeScript bindings when:
- The variable should never be reassigned after initialization.
- You're working with values that should stay constant across the function or module.
- You want better code predictability and fewer bugs.
- You're declaring arrays or objects that you won't reassign but may modify.
In TypeScript, const helps make your intentions clear: this variable won't be redefined.
Examples of Const in TypeScript
Declaring Constants with Primitives
const maxAttempts = 5;
const greeting = "Hello, world!";
const isLoggedIn = true;
Each of these constants is immutable. Any attempt to reassign will cause a compile-time error.
Const Arrays in TypeScript
You can declare arrays with const in TypeScript:
const fruits = ["apple", "banana"];
fruits.push("cherry"); // Allowed
fruits = ["grape"]; // Error: Cannot reassign
The array reference is locked in, but the contents are not. You can add or remove elements, just not reassign the whole array.
If you need a truly immutable array, you can use readonly
arrays:
const numbers: readonly number[] = [1, 2, 3];
numbers.push(4); // Error: push does not exist on readonly array
Const Objects in TypeScript
You can also declare objects as constants:
const user = {
name: "Alex",
age: 28
};
user.age = 29; // OK
user = { name: "Sam", age: 30 }; // Error
Again, you're allowed to change properties but not the object itself.
Const with Functions
You can assign a function to a const:
const sayHi = () => {
console.log("Hi!");
};
sayHi();
This pattern is common in TypeScript, especially with arrow functions.
Const Enums in TypeScript
TypeScript supports const enum
, which lets you create optimized enumerations:
const enum Direction {
Up,
Down,
Left,
Right
}
const move = Direction.Up;
With const enum
, TypeScript replaces enum references with their numeric values during compilation, reducing bundle size.
For example:
console.log(Direction.Left);
Compiles to:
console.log(2);
This makes const enum TypeScript
declarations perfect for performance-critical scenarios.
Learn More About TypeScript Const and Related Concepts
as const
in TypeScript
TypeScript allows you to assert literal types using the as const
syntax. This freezes the shape and value of the data completely:
const point = [10, 20] as const;
Without as const
, point
has the type number[]
. With as const
, the type becomes readonly [10, 20]
.
Here’s a more practical example:
const userRole = {
type: "admin",
level: 5
} as const;
Now type
is the literal "admin"
, and level
is the literal 5
.
This is especially helpful in discriminated unions, component props, and ensuring that types do not widen unexpectedly.
Type Inference with Const
TypeScript infers literal types better with const declarations compared to let
or var
.
const color = "blue"; // type: "blue"
let color2 = "blue"; // type: string
With const, the variable gets the most specific type, which improves code intelligence and error checking.
Using Const in Loops
A common question: can you use const in a loop? Yes, but only if you declare it inside the loop block.
for (const item of [1, 2, 3]) {
console.log(item);
}
Each loop iteration creates a new binding of item
, so there's no problem with reassigning.
However, this doesn’t work:
const i = 0;
while (i < 5) {
i++; // Error: Assignment to constant variable
}
In this case, you’d need let
instead.
Const vs Let in TypeScript
In TypeScript, both const
and let
are block-scoped, but they serve different purposes. Use const
when you don’t intend to reassign the variable after its initial declaration. It signals that the binding should remain fixed, which helps prevent bugs related to accidental reassignment.
On the other hand, use let
when you do need to update the variable’s value later—for example, in loops or conditional logic. While both declarations provide better scoping than the older var
, const
encourages immutability and clearer intent. As a rule of thumb, default to const
, and reach for let
only when reassignment is necessary. This simple habit leads to more predictable and maintainable code.
Const in TypeScript Objects and Arrays
TypeScript const array usage is everywhere in modern code. You can declare constants for fixed configuration options, dropdown values, status indicators, and more.
const ROLES = ["admin", "user", "guest"] as const;
type Role = typeof ROLES[number]; // "admin" | "user" | "guest"
This is a powerful combination of const with as const
and typeof
.
Const with Destructuring
You can use const while destructuring arrays and objects:
const [first, second] = [10, 20];
const { name, age } = { name: "Taylor", age: 33 };
These bindings behave like any other const—no reassignment allowed.
Const in TypeScript Interfaces and Types
Const doesn’t just apply to variables—it also plays a role in working with types. You might use const assertions to freeze the shape of an object used in an interface:
const STATUS = {
ACTIVE: "active",
INACTIVE: "inactive"
} as const;
type Status = typeof STATUS[keyof typeof STATUS];
This is cleaner and safer than using loose strings everywhere.
Best Practices for Using Const in TypeScript
- Use
const
by default. Only fall back tolet
when you must reassign. - Use
as const
to lock down values and prevent unintended changes. - Use
readonly
or immutable patterns if you want to prevent internal changes to arrays and objects. - Use const enums when performance matters and you don’t need runtime access.
- Combine const with type inference to get the most out of TypeScript’s type checker.
TypeScript const bindings provide clarity and safety in your code. They reduce bugs by eliminating accidental reassignments and help the compiler do its job more effectively.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.