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.
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:
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, change the file extensions other than index.js from .js to .tsx . App.js is a target file.
After that, you will be able to launch the app like below:
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.
Happy type safe coding!!
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.