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

Summary of MySQL password modification methods

Methods for changing passwords before MySQL 5.7: ...

XHTML Getting Started Tutorial: Commonly Used XHTML Tags

<br />Just like an article, our web pages sh...

HTML multi-header table code

1. Multi-header table code Copy code The code is a...

MySQL Optimization: Cache Optimization (Continued)

There are caches everywhere inside MySQL. When I ...

Detailed explanation of basic syntax and data types of JavaScript

Table of contents Importing JavaScript 1. Interna...

13 Most Frequently Asked Vue Modifiers in Interviews

Table of contents 1. lazy 2.trim 3.number 4.stop ...

27 Linux document editing commands worth collecting

Linux col command The Linux col command is used t...

Perfect Solution for No rc.local File in Linux

Newer Linux distributions no longer have the rc.l...

Detailed explanation of asynchronous programming knowledge points in nodejs

Introduction Because JavaScript is single-threade...

Detailed explanation of Vuex overall case

Table of contents 1. Introduction 2. Advantages 3...

A brief analysis of the game kimono memo problem

Today, after the game was restarted, I found that...

How to build pptpd service in Alibaba Cloud Ubuntu 16.04

1. To build a PPTP VPN, you need to open port 172...