Static Code Checking
One of the most important concepts to grasp about TypeScript is that its code checking (including type checking) takes place before runtime.
To run a TypeScript file it first needs to be compiled to pure JavaScript. During compilation, all TypeScript code is removed with the exclusion of the TypeScript extensions to JavaScript such as enums.
// myApp.ts
let foo: string = 'foo'
let bar: number = 42
function calculateArea(length: number, width: number): number {
return length * width
}
The above code cannot be executed by any JavaScript engine as JavaScript engines simply do not understand TypeScript. Let's try to execute the myApp.ts
file with Node.js
runtime environment that runs on the V8 engine.
$ node myApp.ts
# let foo: string = 'foo'
# SyntaxError: Unexpected token ':'
It throws Syntax Error
. Therefore, the TypeScript code first needs to be compiled to pure JavaScript. To compile TypeScript code into JavaScript code use TypeScript Compiler called tsc
that comes with the TypeScript installation.
$ tsc myApp.ts
After running the compiler the TypeScript code is compiled into the following pure JavaScript code:
// myApp.js
let foo = 'foo';
let bar = 42;
function calculateArea(length, width) {
return length * width;
}
The code checking from type and other perspectives by TypeScript takes place during the above-described compilation from TypeScript code into JavaScript code.
In addition, many code editors such as Visual Studio Code, use TypeScript for code checking during code editing and are capable of presenting the programmer with errors visually even before compilation.