TypeScript in a React Native Project

+15 Mana ✨

A new React Native project is a TypeScript project from the first commit, yet the TypeScript compiler never produces the JavaScript that runs on the device. Two tools read your .tsx files for two different jobs, each with its own config file. Knowing which tool reads which file explains how a project can pass its type check and still fail to bundle, as it does with a half-configured path alias.

Key terms

  • tsc: the TypeScript compiler, which a React Native project runs only to report type errors.
  • @react-native/babel-preset: the Babel preset that lists the transformations React Native applies to your source.
  • @react-native/typescript-config: the package with the base tsconfig.json that the template's own config extends.
  • paths: the compilerOptions entry in tsconfig.json that maps an import specifier such as @components/* to folders in your project.
  • babel-plugin-module-resolver: the Babel plugin that handles the Babel half of a path alias.

Babel builds the bundle, tsc checks it

When Metro bundles your app, it runs Babel on the source files it bundles: React Native's Metro defaults set Metro's Babel transformer to @react-native/metro-babel-transformer. TypeScript sources are transformed by Babel during that step, and the template's babel.config.js holds a single preset, module:@react-native/babel-preset, with no plugins. The TypeScript compiler is recommended for type checking only, and a new app is set up that way.

That makes the type check a separate command. Run npx tsc (or yarn tsc) from the project root. The template's package.json has the scripts android, ios, lint, start and test, and none of them runs tsc, so add npx tsc to your CI or a pre-push hook yourself.

Two file rules come with this setup. A .jsx file is treated as JavaScript and is not type-checked, although JavaScript and TypeScript modules can import each other. And index.js, which registers your root component with AppRegistry.registerComponent, should stay JavaScript, because converting it can cause problems when you bundle a production build.

Reading the template's tsconfig

The template's tsconfig.json only extends @react-native/typescript-config, includes **/*.ts and **/*.tsx, and excludes **/node_modules and **/Pods. Every compiler option comes from the base config in that package, which the template pins to the same React Native release, next to typescript at ^6.0.3. These are the options you will notice day to day:

  • noEmit: true, so tsc writes no JavaScript and only reports errors.
  • strict: true, so strict mode is on from the first file.
  • isolatedModules: true, jsx: "react-native" and allowJs: true.
  • moduleResolution: "bundler" with customConditions: ["react-native"].
  • skipLibCheck: true, which keeps errors from third-party .d.ts files out of your results.
  • target and module set to esnext, and types: ["jest"] for the Jest globals.

One alias, two configs

An alias lets a screen write import {PrimaryButton} from '@components/PrimaryButton' instead of counting ../ segments. Since Babel and tsc each read your imports, the alias has to be configured twice: once for TypeScript and once for Babel. With only the TypeScript half, npx tsc passes and the alias is still missing from the build.

The TypeScript half is a paths entry in compilerOptions. The tsconfig.json example maps @components/* to ./src/components/*, with a leading ./ and no baseUrl. That differs from the path-alias example on the TypeScript page, which sets "baseUrl": "." with targets like "src/*", a pattern TypeScript 6 rejects. TypeScript 6 deprecates baseUrl, so setting it to any value raises error 5101 (the option will stop functioning in TypeScript 7.0, and "ignoreDeprecations": "6.0" only silences the message). Remove it and keep a target without ./, and you get error 5090:

text
Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?

Without baseUrl, targets resolve against the folder of the tsconfig.json that declares paths, so ./src/components/* means the src/components folder next to that file.

For the Babel half, install the plugin as a dev dependency:

bash
npm install --save-dev babel-plugin-module-resolver

Then register it in babel.config.js, whose syntax differs from tsconfig.json. In the babel.config.js example, the plugin entry is 'module-resolver' and its alias option maps '@components' to './src/components', with no /* on either side. Keep the template's preset there. The docs' version of this file lists module:metro-react-native-babel-preset, which is not the preset a new project uses.

Code Examples

json
{
  "extends": "@react-native/typescript-config",
  "compilerOptions": {
    "paths": {
      "@components/*": ["./src/components/*"]
    }
  },
  "include": ["**/*.ts", "**/*.tsx"],
  "exclude": ["**/node_modules", "**/Pods"]
}
javascript
module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./src'],
        extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
        alias: {
          '@components': './src/components',
        },
      },
    ],
  ],
};
✓ Completed