Setting up TypeScript

To add TypeScript to a project, you'll need to add the typescript package, configure TypeScript, and use Babel to compile TypeScript files.

Install TypeScript

Install the typescript package, tslint for linting, and other supporting packages.

See the full list in Mashup Garage's defaults repo.

Create TypeScript configuration

Create the file tsconfig.json wherever the top-level package.json is in your project. For Node.js projects, that'd be the root folder; for Elixir projects, that might be /assets.

See our recommend configuration files in Mashup Garage's defaults repo.

Update webpack.config.js

Update your Webpack config to allow compilation of .ts and .tsx files.

If your project is already using babel-loader, this configuration may already be there, and you just to update the test value to include TypeScript's extensions. Otherwise, you might need to add the entire module.rules[] section as necessary below.

See our recommended Webpack and Babel configs in Mashup Garage's defaults repo.

Rename files

Rename your .js to .ts and .jsx files to .tsx. There are many ways to accomplish this. Here are a few pointers.

Additional notes

Avoid using ts-loader

Avoid using ts-loader. We strongly recommend using Babel (babel-loader) to compile TypeScript files instead of tsc (ts-loader).

  • Babel is much faster than tsc. While tsc is a full type-checker and compiler, Babel will not do any type-checking, leading to faster compile times.
  • Not using tsc means features that rely on emitting are disabled. While this seems like a bad idea,
  • Most of MG projects already use Babel, so migrating to TypeScript using the same JavaScript compiler is the most practical path to updating to TypeScript.
  • Install @types and typescript to devDependencies

More notes

  • Add linting and formatting. After setting up TypeScript, add Tslint and Prettier afterwards to improve your coding experience.

  • Always use strict: true. The configuration outlined above already includes this rule. This disallows implicit any types, which should lessen chances of running into false positives (ie, TypeScript allowing something that will cause runtime type errors).

  • Avoid using eslint. TypeScript support in eslint is very limited (as of Feb 2019). Tslint provides most of the Eslint rules that matter, while also providing many TypeScript-specific rules.

Further reading