Static Code Checking in TypeScript

What Is Static Code Checking in TypeScript?

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.

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.