Using TypeScript in React Native Project

Using TypeScript in React Native Project

TypeScript in React Native Project

TypeScript is a strongly-typed superset of JavaScript.

TypeScript completes JavaScript adding strongly type declarative structure.

TypeScript uses JavaScript and C# syntax and complies with native JavaScript.

Today, TypeScript is being used to build large open-source projects such as Angular.

TypeScript was developed by Microsoft for the developers who want to build scalable applications in JavaScript and bring their knowledge and experience of structured and modern programming languages such as C# and C++.

A C# developer can use classes, types, objects, their properties and methods and without too much worry about JavaScript syntax.

TypeScript uses a transcompiler or transpiler, a source-to-source compiler that translates TypeScript code into JavaScript code.

Here are the key features of TypeScript.

  1. Developed Microsoft, is an open-source programming language that adds types to JavaScript. TypeScript runs on any platform, any device, and in any browser. TypeScript source code and project is available on github.

  2. Adds optional types, classes, and modules to JavaScript.

  3. Supports tools for large-scale JavaScript applications for any browser, for any host, on any OS.

  4. Is compiled to clean, readable, standards-based JavaScript.

  5. Extends JavaScript syntax, so any existing JavaScript programs work with TypeScript without any changes.

  6. Is designed for the development of large applications and when compiled it produces JavaScript to ensure compatibility.

  7. The command-line TypeScript compiler can be installed as a Node.js package.

  8. Is supported by most of the popular developer IDEs including Visual Studio, Visual Studio Code, Sublime Text, Atom, Eclipse, Emacs, WebStorm, and Vim.

To use TypeScript in our react native projects:

first create a new project with the init command in CMD

npx react-native init typeScriptExample

Install touch command using npm

npm install touch-cli -g

The next step is to add TypeScript to our project. The following commands will:

  • add TypeScript to your project

  • add React Native TypeScript Transformer to your project

  • initialize an empty TypeScript config file, which we'll configure next

  • add an empty React Native TypeScript Transformer config file, which we'll configure next

  • adds typings for React and React Native

  • Navigate to the new created project folder and run the below commands using yarn

yarn add --dev typescript
yarn add --dev react-native-typescript-transformer
yarn tsc --init --pretty --jsx react
touch rn-cli.config.js
yarn add --dev @types/react @types/react-native

The tsconfig.json file contains all the settings for the TypeScript compiler. The defaults created by the command above are mostly fine, but open the file and uncomment the following line:

{
  /* Search the config file for the following line and uncomment it. */
  // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
}

The rn-cli.config.js contains the settings for the React Native TypeScript Transformer. Open it and add the following:

module.exports = {
  getTransformModulePath() {
    return require.resolve('react-native-typescript-transformer');
  },
  getSourceExts() {
    return ['ts', 'tsx'];
  }
};

Rename the generated App.js and _tests/App.js files to App.tsx. index.js needs to use the .js extension. All new files should use the .tsx extension (or .ts if the file doesn't contain any JSX).

If you tried to run the app now, you'd get an error like object prototype may only be an object or null. This is caused by a failure to import the default export from React as well as a named export on the same line. Open App.tsx and modify the import at the top of the file:

-import React, { Component } from 'react';
+import React from 'react'
+import { Component } from 'react';

Some of this has to do with differences in how Babel and TypeScript interoperate with CommonJS modules. In the future, the two will stabilize on the same behaviour.

At this point, you should be able to run the React Native app.

Adding TypeScript testing infrastructure

React Native ships with Jest, so for testing a React Native app with TypeScript, we'll want to add ts-jest to our devDependencies.

to achieve this we will run the below yarn command

yarn add --dev ts-jest

Then, we'll open up our package.json and replace the jest field with the following:

{
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js"
    ],
    "transform": {
      "^.+\\.(js)$": "<rootDir>/node_modules/babel-jest",
      "\\.(ts|tsx)$": "<rootDir>/node_modules/ts-jest/preprocessor.js"
    },
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache"
  }
}

This will configure Jest to run .ts and .tsx files with ts-jest.

Installing dependency type declarations

To get the best experience in TypeScript, we want the type-checker to understand the shape and API of our dependencies. Some libraries will publish their packages with .d.ts files (type declaration/type definition files), which can describe the shape of the underlying JavaScript. For other libraries, we'll need to explicitly install the appropriate package in the @types/ npm scope.

For example, here we'll need types for Jest, React, and React Native, and React Test Renderer.

Run the yarn command below:

yarn add --dev @types/jest @types/react @types/react-native @types/react-test-renderer