Tackling TypeScript
Please support this book: buy it or donate
(Ad, please don’t block.)

4 How does TypeScript work? The bird’s eye view



This chapter gives the bird’s eye view of how TypeScript works: What is the structure of a typical TypeScript project? What is compiled and how? How can we use IDEs to write TypeScript?

4.1 The structure of TypeScript projects

This is one possible file structure for TypeScript projects:

typescript-project/
  dist/
  ts/
    src/
      main.ts
      util.ts
    test/
      util_test.ts
  tsconfig.json

Explanations:

4.1.1 tsconfig.json

The contents of tsconfig.json look as follows:

{
  "compilerOptions": {
    "rootDir": "ts",
    "outDir": "dist",
    "module": "commonjs",
    ···
  }
}

We have specified that:

4.2 Programming TypeScript via an integrated development environment (IDE)

Two popular IDEs for JavaScript are:

The observations in this section are about Visual Studio Code, but may apply to other IDEs, too.

One important fact to be aware of is that Visual Studio Code processes TypeScript source code in two independent ways:

4.3 Other files produced by the TypeScript compiler

Given a TypeScript file main.ts, the TypeScript compiler can produce several kinds of artifacts. The most common ones are:

TypeScript is often not delivered via .ts files, but via .js files and .d.ts files:

A source map specifies for each part of the output code in main.js, which part of the input code in main.ts produced it. Among other things, this information enables runtime environments to execute JavaScript code, while showing the line numbers of the TypeScript code in error messages.

4.3.1 In order to use npm packages from TypeScript, we need type information

The npm registry is a huge repository of JavaScript code. If we want to use a JavaScript package from TypeScript, we need type information for it:

The declaration files of DefinitelyTyped reside in the @types namespace. Therefore, if we need a declaration file for a package such as lodash, we have to install the package @types/lodash.

4.4 Using the TypeScript compiler for plain JavaScript files

The TypeScript compiler can also process plain JavaScript files:

This is an example of a JSDoc comment that provides static type information for a function add():

/**
 * @param {number} x - The first operand
 * @param {number} y - The second operand
 * @returns {number} The sum of both operands
 */
function add(x, y) {
  return x + y;
}

More information: Type-Checking JavaScript Files in the TypeScript Handbook.