Variables
let and const
ts
let score: int = 0;
const MAX_SCORE: int = 9999;
score = score + 10;
score += 5;
console.log(score, MAX_SCORE);letdeclares a variable you can reassign.constdeclares one you cannot. It must have a value.
Both are block-scoped: a variable declared inside { } is not visible outside it.
ts
let x: int = 10;
{
let inner: int = 20;
console.log(x + inner); // 30
}
console.log(x); // 10var still parses, but it is deprecated and the checker warns. Use let or const.
Always write the type
ts
let name: string = "Ada";
let speed: float = 1.5;
let alive: boolean = true;
let inventory: Array<string> = [];
console.log(name, speed, alive, inventory.length);Leaving the type off (let name = "Ada";) earns warning PF071. Inference exists, but explicit types are the house style and keep the intent clear.
Several at once
ts
let a: int = 1, b: int = 2, c: int = 3;
console.log(a + b + c);Compound assignment
ts
let n: int = 10;
n += 5; // 15
n -= 3; // 12
n *= 2; // 24
n /= 4; // 6, integer division
n %= 4; // 2
n **= 3; // 8
console.log(n);Only a variable, a property (a.b, a[i]) or, for plain =, a destructuring pattern can be assigned to. f() = 3 or (n + 1) = 2 is a compile error.
Bitwise forms work too: <<=, >>=, &=, |= and ^=.
Destructuring
Pull values out of an array or a tuple in one line:
ts
const [first, second]: Array<int> = [1, 2];
console.log(first, second);Shadowing
Declaring a variable with the same name as one in an outer scope is allowed, but the checker warns. Names that start with _ are exempt.
Constants are inlined
A const set to a literal number, string or boolean is replaced by its value wherever it is used, so it costs nothing at run time. The same goes for static const on a class.