Implementation of TypeScript in React project

Implementation of TypeScript in React project

1. Introduction

Using TypeScript alone does not lead to a high learning cost, but most front-end developers' projects rely on frameworks.

For example, when used in combination with frameworks such as Vue and React, there will be a certain threshold

To write react code using TypeScript, you need to install @types/react and @types/react-dom in addition to the typescript library.

npm i @types/react -s
npm i @types/react-dom -s

The reason for using @types libraries is that many JavaScript libraries do not provide their own TypeScript declaration files.

Therefore, ts does not know the types of these libraries and the corresponding exported content. Here @types is actually the DefinitelyTyped library in the community, which defines the declarations of most JavaScript libraries currently on the market.

So when you download the corresponding @types declaration of the relevant javascript, you can use the corresponding type definition of the library

2. Usage

When writing react projects, the most commonly used components are:

  • Stateless Components
  • Stateful Components
  • Controlled Components

Stateless Components

The main function is to display the UI. If declared using js, it would be as follows:

import * as React from 'react'

export const Logo = props => {
    const { logo, className, alt } = props

    return (
        <img src={logo} className={className} alt={alt} />
    )
}

But at this time ts will have an error prompt, the reason is that the porps type is not defined, at this time you can use the interface interface to define porps, as follows:

import * as React from 'react'

interface IProps {
    logo?: string
    className?: string
    alt?: string
}

export const Logo = (props: IProps) => {
    const { logo, className, alt } = props

    return (
        <img src={logo} className={className} alt={alt} />
    )
}

But we all know that there is a children property in props, and we cannot define one more child in each porps interface, as follows:

interface IProps {
    logo?: string
    className?: string
    alt?: string
    children?: ReactNode
}

A more standardized way of writing is to use the FC property defined in React, which has already defined the children type, as follows:

export const Logo: React.FC<IProps> = props => {
    const { logo, className, alt } = props

    return (
        <img src={logo} className={className} alt={alt} />
    )
}

  • React.FC explicitly defines the return type, other methods are implicitly deduced
  • React.FC provides type checking and auto-completion for static properties: displayName, propTypes, defaultProps
  • React.FC provides implicit typing for children (ReactElement | null)

Stateful Components

Can be a class component with props and state attributes

If you use typescript declaration, it will look like this:

import * as React from 'react'

interface IProps {
  color: string,
  size?: string,
}
interface IState {
  count: number,
}
class App extends React.Component<IProps, IState> {
  public state = {
    count: 1,
  }
  public render () {
    return (
      <div>Hello world</div>
    )
  }
}

The above uses generics to define the types of props and state, so that you can get better smart prompts in the compiler when using them.

For the definition of the Component generic class, you can refer to the React type definition file node_modules/@types/react/index.d.ts, as shown below:

class Component<P, S> {

    readonly props: Readonly<{ children?: ReactNode }> & Readonly<P>;

    state: Readonly<S>;

}

As can be seen above, the state property also defines a readable type in order to prevent direct calls to this.state to update the state.

Controlled Components

The characteristic of a controlled component is that the content of the element is controlled by the state of the component.

Since the events inside the component are synthetic events, they are not equivalent to native events.

For example, an input component modifies its internal state. The common definition is as follows:

private updateValue(e: React.ChangeEvent<HTMLInputElement>) {
    this.setState({ itemText: e.target.value })
}

Common Event object types:

  • ClipboardEvent<T = Element> Clipboard event object
  • DragEvent<T = Element> drag event object
  • ChangeEvent<T = Element> Change event object
  • KeyboardEvent<T = Element> keyboard event object
  • MouseEvent<T = Element> Mouse event object
  • TouchEvent<T = Element> touch event object
  • WheelEvent<T = Element> Wheel event object
  • AnimationEvent<T = Element> animation event object
  • TransitionEvent<T = Element> transition event object

T receives a DOM element type

Conclusion

The above is just a simple use of typescript in react projects, but when writing react projects, there are also hooks, default parameters, and stores, etc.

The learning cost of using typescript in the framework is relatively high, and you need to write it continuously to become proficient

This is the end of this article about the implementation of TypeScript in React projects. For more content about the application of TypeScript in React projects, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React+ts realizes secondary linkage effect
  • Summary of the use of TypeScript in React projects
  • TypeScript generic parameter default types and new strict compilation option
  • Step by step guide to build a calendar component with React
  • Practical tips for TS type filtering in front-end React Nextjs

<<:  Why MySQL should avoid large transactions and how to solve them

>>:  Analysis of MySQL Aborted connection warning log

Recommend

How to implement the observer pattern in JavaScript

Table of contents Overview Application scenarios ...

How to optimize MySQL group by statement

In MySQL, create a new table with three fields, i...

Detailed example of sorting function field() in MySQL

Preface In our daily development process, sorting...

MYSQL unlock and lock table introduction

MySQL Lock Overview Compared with other databases...

Linux Dig command usage

Dig Introduction: Dig is a tool that queries DNS ...

docker logs - view the implementation of docker container logs

You can view the container logs through the docke...

How to install PostgreSQL and PostGIS using yum on CentOS7

1. Update the yum source The PostgreSQL version o...

Nginx uses the Gzip algorithm to compress messages

What is HTTP Compression Sometimes, relatively la...

WeChat applet realizes left-right linkage

This article shares the specific code for WeChat ...

How to set the default value of a MySQL field

Table of contents Preface: 1. Default value relat...

Example of how to modify styles via CSS variables

question How to modify CSS pseudo-class style wit...

XHTML tutorial, a brief introduction to the basics of XHTML

<br />This article will briefly introduce yo...