Create a React + typescript project:

npx create-react-app my-app --typescript

Existing projects migrate to typescript:

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

TypeScript tutorial

1. Introduce plug-ins

The introduction of external plugins in typescript not only introduces the plug-in itself but also its declaration @types, @Type manages the declaration files of third-party libraries. React-router-dom NPM I react-router-dom NPM I @types/react-router-dom

Find the declaration file: Microsoft. Making. IO/TypeSearch /

2. Configure routes in the TS

When you use withRouterts with @types/react-router-dom you will always get an error (ts2339) because you need to use RuoteComponentProps.

import React from 'react';
import { withRouter, RouteComponentProps } from 'react-router-dom';

type PropsType = RouteComponentProps & {};

class demo extends React.Component<PropsType, any> {
  
  constructor(props: PropsType) {
    super(props);
    this.state = {
      demo: 'demo',}}goBack() {
    this.props.history.goBack();
  }

  render() {
    return (
      <div>
        <button onClick={() => this.goBack()}>goBack</button>
      </div>
    )
  }
}

export default withRouter(demo);
Copy the code

3. Use of props and state

When you use props or state in the React component, you need to pass two parameters to the component: types and shape. Because of the TS rule, everything should work the way it’s supposed to.

React.Compnent<types, shape>
Copy the code

If the type does not match ts, an error will be reported:

Should correspond to type:

When you are not sure how many parameters and parameter types you need to create, use any (any type) :

class demo extends React.Component<any, any>
Copy the code

Passing RuoteComponentProps to the component defines any. If you are a normal group without routing plug-ins, note that if types in React.Compnent

are defined, you cannot take the parameters from the route.
,>

this.props.history.push({
  pathname: 'demo',
  state: {
    data: 1
  }
})
Copy the code


demoData
any

React + TypeScript is a bit of a hassle to get used to when using TS for the first time. It’s also a hassle to get used to the declarations and special handling of the React routing plugin.