typescript

2019-05-23

create react-native project and develop it by applying typescript.

create react-native project

create RN project with below command.

react-native init proejct-name

install required libraries for typescript

install required libraries for applying typescript to the project.

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

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": {
    "target": "es2015",
    "module": "commonjs",
    "moduleResolution": "node",
    "noResolve": false,
    "noImplicitAny": false,
    "removeComments": false,
    "allowJs": true,
    "jsx": "react",
    "allowSyntheticDefaultImports": true,
    "typeRoots": ["./node_modules/@types", "./src/@types"]
  },
  "exclude": [
    "node_modules",
    "dest",
    "android",
    "ios",
    "acceptance-tests",
    ".jest",
    "src/setupTests.ts",
    "./node_modules/**/*"
  ],
  "include": ["./node_modules/@types", "./src/**/*", "./src/@types"]
}

if you want more detail, see official website.

create tslint.json

configure tslint to help typescript development. create tslint.json in the project root folder and copy-paste below contents.

{
    "extends": [],
    "defaultSeverity": "warning",
    "linterOptions": {
      "exclude": [
        "config/**/*.js",
        "node_modules/**/*.ts"
      ]
    }
}

if you want more detail, see official website.

create rn-cli.config.js

we got the comment(No need for rn-cli.config.js anymore since v0.57) on facebook from Bruno Lemos and we checked it. it doesn’t need anymore to create rn-cli.config.js since RN(react-native) version 0.57.

this setting help RN to recognize typescript at runtime. create rn-cli.config.js file in the project root folder and copy-paste below contents.

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

code with typescript

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

import * as React from 'react';
...
interface Props {}
interface State {}
...
export default class App extends React.Component<Props, State> {
Buy me a coffeeBuy me a coffee
Posts