Setting up

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.

yarn add typescript

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.

 "compilerOptions": {
   // Target latest version of ECMAScript
   "target": "esnext",

   // Search under node_modules for non-relative imports
   "moduleResolution": "node",

   // Process & infer types from .js files
   "allowJs": true,

   // Don't emit. Use Babel to transform files
   "noEmit": true,

   // Enable strictest settings like strictNullChecks & noImplicitAny
   "strict": true,

   // Use JSX
   "jsx": "react"
 "include": [
   // Change this to the paths where JS and TypeScript files are stored.

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.

module.exports = {
  module: {
    "rules": [
        test: /\.(js|jsx|ts|tsx)$/,
        exclude: /node_modules/,
        use: [
          { loader: 'babel-loader' }

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.

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).

  • Don't use 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