TypeScript Introduction
TypeScript is JavaScript with a type layer added on top. The compiler checks the types and then emits plain JavaScript.
An annotated variable
A colon and a type name after the variable name give the variable its type.
let score: number = 10;
score = 15;
console.log(score);A wrong type is refused
The same variable cannot take a string. The compiler stops the program before it runs.
let points: number = 8;
points = "eight";
console.log(points);A second annotated variable
The annotation stays in place while the value changes.
let level: number = 2;
level = level + 1;
console.log(level);Example
let price: number = 20;
let quantity: number = 3;
let total: number = price * quantity;
console.log(total);Key points
- A type layer states the kind of value each variable can hold.
- Use a colon and a type name to annotate a variable.
- The compiler is called tsc.
- tsc checks the types before the code runs.
- tsc emits plain JavaScript when the check passes.
- The JavaScript course is the base for this course.
In this example, price holds 20 and quantity holds 3. Both variables carry the number type. The total line multiplies the two values and stores 60. The log line prints 60.
Note
Type annotations disappear from the emitted JavaScript.
Try it Yourself
Edit the code, then press Run.
Running is simulated Β· TypeScript Playground
Exercise
What does the TypeScript compiler do first?