TypeScript Tutorial
TypeScript Syntax
Statements end with a semicolon. Blocks use braces. The compiler cares about types, not indentation.
A program is statements from the top
TypeScript reads a file from top to bottom. There is no main. Execution starts at the first statement. Each statement ends with a semicolon. Types sit next to names so tsc can check them.
Example
const n: number = 3;
console.log(n);Open examples with Try it in TypeScript. That is /typescript/try: a tsc compile-and-run editor.
Semicolons
Forget a semicolon and tsc may complain on the next line. Python uses newlines. TypeScript uses; so you can put more than one statement on a line — you usually should not.
Example
const a: number = 1;
const b: number = 2;
console.log(a + b);JavaScript will sometimes insert a semicolon for you. This tutorial always writes them. That habit matches C++ on StudyGrid and keeps the file obvious to tsc.
Braces mark blocks
{ } groups statements: the body of an if, a loop, a function. Indentation is for people. The compiler only sees braces and types. Mismatched braces are a common first-week error.
Example
const show: boolean = true;
if (show) {
console.log("inside the block");
}Case and names
TypeScript is case-sensitive. Console is not console. Log is notlog. Names start with a letter or underscore, then letters, digits, or underscores. Do not start a name with a digit.
| Valid | Invalid |
|---|---|
| count, player2, _tmp | 2player, my-score, class |
class is a keyword. You cannot use it as a variable name. The compiler will say so. The same goes for let, const, and function.
Whitespace
Spaces and blank lines do not change meaning. Use them so a human can scan the file. One statement per line is the house style on StudyGrid.
Indentation does not create a block the way it does in Python. If you indent a line but forget the braces, tsc will not treat that line as inside the if.
Types are part of the line
Write the name, a colon, then the type: const n: number = 3;. That annotation is syntax, not a comment. Wrong types are errors. Leave the annotation off and tsc still infers a type from the value — this tutorial writes the type so you can see it.
Example
const label: string = "count";
const count: number = 3;
console.log(label + " is " + count);Next: how console.log prints values.