First published at: github.com/USTB-musion…

Writing in the front

Typescript is a superset of JavaScript that provides a type system and support for ES6. I have been using TS to write React for nearly 3 months, during which I stepped on a lot of holes. From the beginning, I thought TS was unnecessary, to now I think TS is really sweet. Here’s a summary of how to write React with TS.

This paper will summarize from the following parts:

  1. The advantage of the Typescript
  2. TS is used with React
  3. conclusion
  4. See links and further reading

The advantage of the Typescript

1. Help refactor your code better

A good code habit is to always make small refactorings of your code to make it more maintainable. But for a lot of code running online, code test coverage is often not very high, sometimes even a variable name change, will affect the whole. Projects written in TS have no such concerns. The STATIC checking feature of TS helps find the parts of the code that have errors.

2. IDE tips like vscode are smarter

Js is a dynamically weakly typed interpretation language. The type of a variable can be changed after it is declared, and the type must be determined at run time. Ts displays an error at compile time, not run time. So using features like static type checking that TS brings with it will make the IDE’s hints even better.

3. Type declarations are great documentation in and of themselves

When you’re working on a project with historical baggage, you’re going to have to worry about the lack of documentation and code comments. For TS, it’s possible to make the code as documentation by declaring what fields mean and what fields are required and optional. As a simple example, when encapsulating a button component:

export interface ButtonProps { style? : React.CSSProperties className? : string label? : React.ReactNode type? : 'primary' | 'default' | 'search' size? : 'sm' | 'md' | 'lg' | 'mini' disabled? : boolean title? : string onClick? : ((e: React.MouseEvent<HTMLButtonElement>) => void) }Copy the code

As you can see from these declarations, when using the Button file, style is an optional value that represents a style field that you can customize. Type is also an optional value that indicates the color type of the button, which can be ‘primary’,’default’, or ‘mini’. Disabled is also an optional value. The value passed in must be of Boolean type. So you can see that type declarations themselves are pretty good documentation.

TS is used with React

Use of class components

This is an example of creating the Props and State interfaces. The Props interface accepts the name and enthusiasmLevel parameters and the State interface accepts the currentEnthusiasm parameter.

import * as React from "react"; export interface Props { name: string; enthusiasmLevel? : number; } interface State { currentEnthusiasm: number; } class Hello extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { currentEnthusiasm: props.enthusiasmLevel || 1 }; } onIncrement = () => this.updateEnthusiasm(this.state.currentEnthusiasm + 1); onDecrement = () => this.updateEnthusiasm(this.state.currentEnthusiasm - 1); render() { const { name } = this.props; if (this.state.currentEnthusiasm <= 0) { throw new Error('You could be a little more enthusiastic. :D'); } return ( <div className="hello"> <div className="greeting"> Hello {name + getExclamationMarks(this.state.currentEnthusiasm)} </div> <button onClick={this.onDecrement}>-</button> <button onClick={this.onIncrement}>+</button> </div> ); } updateEnthusiasm(currentEnthusiasm: number) { this.setState({ currentEnthusiasm }); } } export default Hello; function getExclamationMarks(numChars: number) { return Array(numChars + 1).join('! '); }Copy the code

Use of stateless components

Stateless components are also called dumb components. A component can be called stateless if it does not have its own state inside it. SFC<P = {}> = StatelessComponent is defined at @types/react

. When we write stateless components, we can specify our component as SFC or StatelessComponent. It’s already predefined for children, displayName, etc. Take Button as an example:

import React from 'react'

const Button = ({ onClick: handleClick, children }) => (
  <button onClick={handleClick}>{children}</button>
)
Copy the code

A stateless component written in TS looks like this:

import React, { MouseEvent, SFC } from 'react';

type Props = { onClick(e: MouseEvent<HTMLElement>): void };

const Button: SFC<Props> = ({ onClick: handleClick, children }) => (
  <button onClick={handleClick}>{children}</button>
);
Copy the code

readonly

React: this.props. XXX and this.state. XXX cannot be modified directly, so state and props can be marked immutable:

interface Props { readonly number: number; } interface State { readonly color: string; } export class Hello extends React.Component<Props, State> { someMethod() { this.props.number = 123; // Error: props is immutable this.state.color = 'red'; // Error: you should use this.setState()}}Copy the code

Handling Event Objects

In your work, you may often use Event objects, such as React.ChangeEvent for change or React.ChangeEvent for click.

  onClick = (e: React.MouseEvent<HTMLButtonElement>) => {
      // do something
  }
  
  onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      // do something
  }
Copy the code

Renderable interface

React can render something like JSX or string, which is incorporated into the type react. ReactNode, so you can use it when you receive renderable content:

type Props = {
  header: React.ReactNode;
  body: React.ReactNode;
};

class MyComonent extends React.Component<Props, {}> {
  render() {
    return (
      <div>
        {this.props.header}
        {this.props.body}
      </div>
    );
  }
}

<MyComponent header={<h1>Header</h1>} body={<i>body</i>} />
Copy the code

conclusion

In large and medium-sized front-end projects, many errors are discovered at runtime due to the dynamic and weakly typed nature of JS. Ts, as a superset of JS, brings compile-time checks for front-end development and avoids many errors in the compilation stage. It also brings more intelligent hints to the IDE. Although learning TS will take some time, it will be well worth the time. After using TS to develop projects, it is obvious that the project is more maintainable, the bug rate is lower, and the documentation is easier to check. You can understand the meaning of each field by looking at the type declaration file.

See links and further reading

The ultimate React component pattern in TypeScript 2.8

Understand TypeScript in depth

TypeScript-React-Starter

You can pay attention to my public account “Muchen classmates”, goose factory code farmers, usually record some trivial bits, technology, life, perception, grow together.