Variables and let/const
Declare variables with let and const and give them types.
Syntax
let age: number = 30;
const pi: number = 3.14;Like modern JavaScript, TypeScript uses let for values that can change and const for values that cannot be reassigned. You can add a type after the variable name with a colon.
let vs const
const— cannot be reassigned. Prefer this by default.let— use when the value needs to change.
Avoid var; it has confusing scoping rules.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A developer uses const for an API base URL so the compiler prevents accidental reassignment.
- A loop counter declared with let is typed as number, catching a bug where a string was assigned mid-loop.
- A configuration object declared as const with typed properties prevents callers from adding unknown keys.
More examples
const with explicit type
Declares three constants with explicit primitive type annotations, the most basic form of TypeScript variable typing.
const appName: string = 'SoundsCode';
const maxRetries: number = 3;
const isProduction: boolean = false;let type rejects wrong value
Shows how a typed let variable accepts reassignment to the same type but rejects a value of a different type.
let score: number = 0;
score = 10; // OK
score = 'ten'; // Error: Type 'string' is not assignable to type 'number'Block scoping with let
Illustrates let's block scope inside a for loop, keeping loop variables out of the enclosing function scope.
function processItems(items: string[]): void {
for (let i: number = 0; i < items.length; i++) {
let current: string = items[i];
console.log(current);
}
// i and current are not accessible here
}
Discussion