Configuring TypeScript

When building applications with JavaScript or TypeScript, it’s critical to understand the environment where your code will run. JavaScript operates across multiple platforms, from web browsers to server-side environments like Node.js. Each platform is powered by its own JavaScript engine: Google’s V8, Mozilla’s SpiderMonkey, Apple’s JavaScriptCore, and others. While these engines adhere to the ECMA-262 specification, their implementations and features can differ. Additionally, platforms often provide functionality beyond the standard, so knowing the environment your code runs on is crucial.

Setting Up Your TypeScript Project

Initializing a Node Package

The Node Package Manager (npm) ships with Node.js and supplies a wizard to create new packages using the initializer command:

npm init

To prevent the wizard from asking questions, run the command with the -y flag, which answers all setup questions with "yes":

npm init -y

Once your Node package is initialized, you can add dependencies using npm install. To start a TypeScript project, add TypeScript as a development dependency:

npm install -D typescript

Initializing a TypeScript Configuration File

In order for our code to be compatible with a specific target, we need to configure our TypeScript compiler (tsc) accordingly. This involves creating a configuration file (`tsconfig.json`) that can be generated by executing:

npx tsc --init

This file defines how the TypeScript compiler processes your code. Upon opening it, you’ll find a range of options. For now, focus on the "target" property, which determines the ECMAScript version of the output JavaScript. For example:

{
  "compilerOptions": {
    "target": "ES2016"
    // ...
  }
}

This setting specifies that the compiled JavaScript should conform to the ECMAScript 2016 standard. Make also sure that strict type checking is enabled:

{
  "compilerOptions": {
    "strict": true
    // ...
  }
}

Structuring Your Project

Organize your project by creating a src directory for source files. For example, create a file named src/add.ts for a simple addition function:

function add(a, b) {
  return a + b;
}

When strict type checking is enabled, you will get to see TypeScript error "TS7006":

Parameter 'a' implicitly has an 'any' type.

TypeScript will warn you about missing type annotations or potential issues. Disabling strict checking might suppress these warnings, but doing so undermines TypeScript's primary benefit: robust type safety.

Compilation Basics

Since Node.js doesn’t natively execute TypeScript, you’ll need to compile your .ts files into .js files. Use the following command:

npx tsc

This generates corresponding JavaScript files, which you can run using Node.js:

node src/add.js

Remember to recompile your TypeScript code after making changes; otherwise, your JavaScript files will remain outdated. To simplify this process, TypeScript offers a --watch mode:

npx tsc --watch

This mode continuously monitors your files and recompiles them upon changes.

Automating with npm Scripts

In Node.js projects, it’s typical to define scripts in your package.json file. Add a start script for running your application:

{
  "scripts": {
    "prestart": "npx tsc",
    "start": "node src/add.js",
    "poststart": "echo Goodbye!"
  }
}

Here’s what happens:

  1. The prestart script compiles your TypeScript files.
  2. The start script executes the compiled JavaScript.
  3. The poststart script runs afterward (just for demonstration purposes).

Run your scripts with:

npm start

For custom script names, that are not part of the npm Documentation, use:

npm run custom-script-name

The Pitfalls of Global TypeScript Installation

Many tutorials suggest installing TypeScript globally:

npm install --global typescript

While this allows the tsc command to work system-wide, it introduces versioning issues. For instance, if your global TypeScript version differs from the version specified in your project, inconsistencies can arise during compilation. To avoid this, always use the project-local version via npx tsc.

Here’s an example of the problem:

Install TypeScript version 4 globally using the command:

npm install --global typescript@4
  1. Next, configure the tsconfig.json file with a deprecated TypeScript feature, such as (importsNotUsedAsValues).
  2. With TypeScript version 4 globally installed, you will be able to compile the code using the tsc command.
  3. However, problems arise when your code is executed in an environment that uses TypeScript version 5. In such cases, the compilation will fail due to the deprecated feature being unsupported in the newer version.

To avoid such confusion, it's best to remove the globally installed version by running:

npm uninstall --global typescript

What You Have Learned

Setting Up Your TypeScript Project: You have learned how to initialize a new Node.js package using npm init -y, which automatically answers setup questions. You also learned how to add TypeScript as a development dependency with npm install -D typescript, ensuring your project uses a specific TypeScript version.

Initializing a TypeScript Configuration File: You now know how to create a tsconfig.json file with the npx tsc --init command. This configuration file lets you customize how the TypeScript compiler processes your code. You also learned how to set the "target" property to specify the ECMAScript version for your output JavaScript and enable strict type checking with "strict": true.

Structuring Your Project: You have learned how to organize your TypeScript project by creating a src directory for your source files. You also explored how enabling strict type checking helps catch errors like missing type annotations, making your code more robust.

Compilation Basics: You now understand how to compile TypeScript files using the npx tsc command and how to run the compiled JavaScript with Node.js. You’ve learned about the --watch mode, which automatically recompiles your TypeScript files whenever changes are made.

Automating with npm Scripts: You have learned how to define custom scripts in your package.json file to automate tasks like compiling TypeScript and running your application. You now know how to use the npm start command to execute these scripts.

Global TypeScript Installation: You now understand the problems with globally installing TypeScript, such as version mismatches between the global and project-specific versions. To avoid these issues, you learned to always install the project-local version by running npm install -D typescript instead of installing TypeScript globally.


Quiz

  1. What's the name of the specification that standardizes JavaScript?
  • a) ECMAScript
  • b) JavaScriptCore
  • c) TypeScript Standard
  • d) NodeSpec
  1. Where are TypeScript's compiler configurations saved?
  • a) package.json
  • b) tsconfig.json
  • c) config.ts
  • d) compiler.config
  1. Why should you enable TypeScript's strict mode?
  • a) To make TypeScript compile faster
  • b) To detect potential coding issues early
  • c) To support older JavaScript engines
  • d) To disable additional type checking
  1. How can you compile TypeScript to JavaScript?
  • a) Run node add.ts
  • b) Run npx tsc
  • c) Run npm compile
  • d) Run npm start
  1. What is the purpose of TypeScript's watch mode?
  • a) To debug JavaScript code
  • b) To recompile TypeScript files upon changes
  • c) To watch for typing errors in VS Code
  • d) To update the Node.js runtime
  1. What issues can arise from installing TypeScript globally?
  • a) It prevents the use of IntelliSense
  • b) Version mismatches between the global installation and project-specific installations
  • c) Global installation is slower than local installation
  • d) It disables npm scripts in your project