TypeScript Tutorial
TypeScript Variables
A variable has a type, a name, and a value. Declare it with let or const, then annotate: let count: number = 3;
Declare, then annotate
A variable is a named box. You start with let or const, then the name, then a colon and a type, then a value. tsc knows which operations are allowed. This is unlike Python, where a name appears when you assign to it, and unlike C++, where the type comes first: int count = 3;.
Example
let count: number = 3;
console.log(count);let is the keyword. count is the name. number is the type.3 is the value. The semicolon ends the statement.
Try the examples at /typescript/try with Try it in TypeScript. That editor compiles with tsc.
Assignment changes the value
After a let variable exists, = stores a new value of a compatible type. The old value is gone. You can declare without a value and assign later — but you must assign before you read, or tsc reports an error in strict mode.
Example
let score: number = 0;
score = 10;
score = score + 5;
console.log(score);Change the starting 0 and compile again. The printed number follows the assignments in order.
Do not print a variable you never initialized. Give a starting value, even if that value is 0.
const does not change
Use const when the binding must stay fixed. tsc rejects any later assignment. Use it for names that are really facts: a tax rate, a maximum, a conversion factor.
Example
const daysInWeek: number = 7;
let weeks: number = 3;
console.log(weeks * daysInWeek);Writing daysInWeek = 8; after that declaration is an error. That is the point ofconst. Prefer const until you know the name must be reassigned, then switch tolet.
Several variables
Declare one name per statement. You can list more than one after a single let, separated by commas, but a line per variable is easier to annotate and easier to read.
Example
const x: number = 1;
const y: number = 2;
const z: number = 3;
const width: number = 4.5;
const height: number = 2.0;
console.log(x + y + z);
console.log(width * height);Names
Choose names that say what the value is. TypeScript is case-sensitive: Count is notcount. Start with a letter or underscore. Do not use a keyword such as let ornumber.
| Good | Poor |
|---|---|
itemCount, taxRate, n | x1x2, data, temp2 with no context |
Type stays put
A number stays a number. You cannot store a whole sentence in it. You cannot later turn the same name into a string by assigning "hello". Pick the type that matches the data, then keep using that name for that kind of value.
Next: reading values from the stdin box into those variables.