Add TypeScript support to React Native for Windows

This post has been republished via RSS; it originally appeared at: New blog articles in Microsoft Tech Community.

React Native is an interesting technology!! Theer are many great articles our team blog.

In this article, I will explain to add TypeScript support to a RN4W project.

Create a new RN4W project(JS)

First, we create a new RN4W project in JavaScript. The completely steps are writtn on the official GitHub repository.

Consuming react native windows
https://github.com/microsoft/react-native-windows/blob/master/vnext/docs/ConsumingRNW.md

After doing the steps, we will see following:

KazukiOta_0-1580982883306.png

Add TypeScript support

There is a official document that is "Adding TypeScript to an Existing Project."
https://facebook.github.io/react-native/docs/typescript#adding-typescript-to-an-existing-project

The steps also works for React Native for Windows. So let's type following command:

 

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

 

And adding tsconfig.json like below:

 

{ "compilerOptions": { "allowJs": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "isolatedModules": true, "jsx": "react", "lib": ["es6"], "moduleResolution": "node", "noEmit": true, "strict": true, "target": "esnext", "resolveJsonModule": true }, "exclude": [ "node_modules", "babel.config.js", "metro.config.js", "jest.config.js" ] }

 

There is a different line from the original document. I added "resolveJsonModule": true because in the React Native template app is using import JSON file directly.

And adding jest.config.js like below. This is a same as the original document.

 

module.exports = { preset: 'react-native', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], };

 

The next, rename file extensions from .js to .tsx. There are two target files that are App.js and index.js.

After that, you can launch the app like below:

KazukiOta_0-1580983915027.png

But there is a compile error in App.tsx yet. Adding a following type declare to above of App component definition to fix the error.

 

declare var global: {HermesInternal: null | {}};

 

If you remove global.HermesInternal from App.tsx, then you can remove the row.

After that, you can get intellisence everywhere.

KazukiOta_1-1580984801768.pngKazukiOta_0-1580984776787.png

Happy type safe coding!!

REMEMBER: these articles are SYNDICATED. Your best bet to get a reply is to follow the link at the top of the post to the ORIGINAL post! BUT you're more than welcome to start discussions here:

This site uses Akismet to reduce spam. Learn how your comment data is processed.