How to use TypeScript in React Native

2021-07-04 hit count image

Let's see how to configure TypeScript and how to use TypeScript in React Native.

create react-native project

create React Native project with below command.

npm install typescript @types/react @types/react-native --save-dev

install required libraries for TypeScript

install required libraries for applying TypeScript to the project.

react-native init proejct-name

TypeScript libraries

  • typescript: intsall TypeScript.
  • @types/react: intsll react types for TypeScript.
  • @types/react-native: intall RN type for TypeScript.

TypeScript configuration

configure TypeScript to make react-native work.

create tsconfig.json

create tsconfig.json in the project root folder and copy-paste below contents.

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

if you want more detail, see official website.

Make TypeScript project via React Native CLI

If you feel bothered to configure these all settings, you can use React Native CLI to make React Native project based on TypeScript to use the command below.

npx react-native init SampleProject --template react-native-template-typescript

code with TypeScript

change App.js filename to App.tsx and code with TypeScript style.

  • Class Component
import React from 'react';
...
interface Props {}
interface State {}
...
export default class App extends React.Component<Props, State> {
  • Function Component
import React from 'react';
...
interface Props {}
...
const App = ({  }: Props) => {
...

Completed

Done! we’ve seen how to apply TypeScript to React Native, and how to use TypeScript in React Native. Form now, let’s use TypeScript in React Native to check the types!

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts