Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write React with TypeScript

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to write React in TypeScript". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

How to use React and TypeScript together

Before we begin, let's review how React and TypeScript work together. React is a "JavaScript library for building user interfaces", while TypeScript is a "JavaScript typed superset that can be compiled into plain JavaScript". By using them at the same time, we are actually building UI using a typed version of JavaScript.

The reason for using them together is to get the benefits of statically typed language (TypeScript) for UI: reducing the bug that JS brings and making front-end development more secure.

Will TypeScript compile my React code?

A common question that is often mentioned is whether TypeScript compiles your React code. TypeScript works similar to the following:

TS: "Hey, is this all your UI code?"

React: "Yes!"

TS: "Cool! I'll compile it and make sure you don't miss anything."

React: "sounds good to me!"

Therefore, the answer is yes! But later, when we introduce the tsconfig.json configuration, most of the time you want to use "noEmit": true. This is because normally we just use TypeScript for type checking.

In a nutshell, TypeScript compiles your React code for type checking. In most cases, it does not emit any JavaScript output. The output is still similar to a non-TypeScript React project.

Can TypeScript be used with React and Webpack?

Yes, TypeScript can be used with React and webpack. Fortunately, the official TypeScript manual provides configuration guidelines for this.

I hope this will make it easy for you to understand how both work. Now, get into best practices!

Best practic

We studied the most common problems and sorted out some of the most common writing and configuration of React with TypeScript. In this way, by using this article as a reference, you can follow best practices in your project.

Configuration

Configuration is one of the most boring but important parts of development. How can we complete these configurations in the shortest possible time to provide maximum efficiency and productivity? Let's discuss the following configuration

Tsconfig.json

ESLint / Prettier

VS Code extension and configuration

Project initialization

The quickest way to initialize a React/TypeScript application is to use create-react-app with the TypeScript template. You can run the following command:

Npx create-react-app my-app-template typescript

This allows you to start writing React in TypeScript. Some obvious differences are:

.tsx: TypeScript JSX file extension

Tsconfig.json: TypeScript profile with some default configuration

React-app-env.d.ts:TypeScript declaration file, which can be configured to allow references to SVG.

Tsconfig.json

Fortunately, the latest React/TypeScript automatically generates tsconfig.json with some of the most basic configurations by default. We suggest you modify it to the following:

{"compilerOptions": {"target": "es5", / / specify ECMAScript version "lib": ["dom", "dom.iterable", "esnext"], / / list of dependent library files to be included in compilation "allowJs": true, / / allow compilation of JavaScript file "skipLibCheck": true / / skip type checking of all declaration files "esModuleInterop": true, / / disable namespace references (import * as fs from "fs") enable CJS/AMD/UMD style references (import fs from "fs") "allowSyntheticDefaultImports": true, / / allow default import of "strict": true from modules that do not have default exports / / enable all strict type checking options "forceConsistentCasingInFileNames": true, / / do not allow inconsistent format references to the same file "module": "esnext", / / specify module code generation "moduleResolution": "node", / / use Node.js style parsing module "resolveJsonModule": true / / allow module "noEmit" to be imported with .json extension: true, / / No output (meaning no code compilation Only perform type checking) "jsx": "react", / / support JSX "sourceMap": true in .tsx file, / / generate corresponding .map file "declaration": true, / / generate corresponding .d.ts file "noUnusedLocals": true, / / report error "noUnusedParameters": true of unused local variables / / report errors with unused parameters "experimentalDecorators": true, / / enable experimental support for the ES decorator "incremental": true, / / enable incremental compilation "noFallthroughCasesInSwitch": true} by reading / writing information from previous compilations to files on disk "include": ["src/**/*" / / * TypeScript files should be typed * *], "exclude": ["node_modules", "build"] / / * files without type checking * *}

Other suggestions come from the react-typescript-cheatsheet community

ESLint / Prettier

To ensure that your code follows the rules of the project or team and the style is consistent, it is recommended that you set ESLint and Prettier. To make them work well, follow these steps to set them up.

1. Installation dependency

Yarn add eslint @ typescript-eslint/parser @ typescript-eslint/eslint-plugin eslint-plugin-react-- dev

two。 Create an eslintrc.js file in the root directory and add the following:

Module.exports = {parser:'@ typescript-eslint/parser', / / specify the ESLint parser extends: ['plugin:react/recommended', / / use recommendation rules from @ eslint-plugin-react' plugin:@typescript-eslint/recommended', / / use recommendation rules from @ typescript-eslint/eslint-plugin], parserOptions: {ecmaVersion: 2018 / / allow parsing of the latest ECMAScript feature sourceType: 'module', / / allow import ecmaFeatures: {jsx: true, / / allow parsing of JSX},}, rules: {/ / Custom rules / / e.g. "@ typescript-eslint/explicit-function-return-type": "off",} Settings: {react: {version: 'detect', / / tell eslint-plugin-react to automatically detect the version of React},},}

3. Add Prettier dependency

Yarn add prettier eslint-config-prettier eslint-plugin-prettier-dev

4. Create a .prettierrc.js file in the root directory and add the following:

Module.exports = {semi: true, trailingComma: 'all', singleQuote: true, printWidth: 120, tabWidth: 4,}

5. Update the .eslintrc.js file:

Module.exports = {parser:'@ typescript-eslint/parser', / / specify the ESLint parser extends: ['plugin:react/recommended', / / use recommendation rules from @ eslint-plugin-react' plugin:@typescript-eslint/recommended', / / use recommendation rules from @ typescript-eslint/eslint-plugin 'prettier/@typescript-eslint' / / disable ESLint rule 'plugin:prettier/recommended',] from @ typescript-eslint/ ESLint conflict with prettier using ESLint-config-prettier, parserOptions: {ecmaVersion: 2018, / / allow parsing of the latest ECMAScript feature sourceType:' module', / / allow import ecmaFeatures: {jsx: true, / / allow parsing of JSX},} Rules: {/ / Custom rules / / e.g. "@ typescript-eslint/explicit-function-return-type": "off",}, settings: {react: {version: 'detect', / / tell eslint-plugin-react to automatically detect the version of React},},}

VSCode extensions and Settings

We have added ESLint and Prettier, and the next step is to automatically fix / beautify our code at save time.

First, install ESLint extension and Prettier extension for VSCode. This will integrate ESLint seamlessly with your editor.

Next, update the workspace setting .vscode / settings.json by adding the following to yours:

{"editor.formatOnSave": true}

When you save, VS Code will work its magic and fix your code. That's great!

module

One of the core concepts of React is components. Here, we will reference the standard components since React v16.8, which means using Hook instead of the components of the class.

In general, a basic component has a lot to focus on. Let's look at an example:

Import React from 'react' / / functional declarative writing function Heading (): React.ReactNode {return My Website Heading} / / functional extended writing const OtherHeading: React.FC = () = > My Website Heading

Note the key differences here. In the first example, we use the function declarative method, and we indicate that the return value of this function is of type React.ReactNode. Instead, the second example uses a function expression. Because the second instance returns a function instead of a value or expression, we note that the return value of this function is of type React.FC.

Keep in mind that these two ways can be confusing. This mainly depends on the design choice. No matter which one you choose to use in your project, use it consistently.

Props

The next core concept we will introduce is Props. You can use interface or type to define Props. Let's look at another example:

Import React from 'react' interface Props {name: string; color: string;} type OtherProps = {name: string; color: string;} / / Notice here we're using the function declaration with the interface Props function Heading ({name, color}: Props): React.ReactNode {return My Website Heading} / / Notice here we're using the function expression with the type OtherProps const OtherHeading: React.FC = ({name, color}) = > My Website Heading

With regard to interface or type, we recommend following the guidelines proposed by the react-typescript-cheatsheet community:

When writing a library or third-party environment type definition, always use interface for the definition of the public API.

Consider using type for the State and Props of your React components because it is more constrained. "

Let's look at another example:

Import React from 'react' type Props = {/ * * color to use for the background * / color?: string; / * * standard children prop: accepts any valid ReactNode * / children: React.ReactNode; / * * callback function passed to the onClick handler*/ onClick: () = > void;} const Button: React.FC = ({children, color =' tomato', onClick}) = > {return {children}}

In this component, we use type for Props. There are short instructions at the top of each Props to provide more background information for other developers. ? Indicates that Props is optional. Children props is a React.ReactNode that means it is also a React component.

In general, when writing Props in React and TypeScript projects, keep the following points in mind:

Always use the TSDoc tag to add descriptive comments to your Props / * * comment * /.

Whether you use type or interfaces for component Props, you should always use them.

If props is optional, handle it appropriately or use the default value.

Hooks

Fortunately, TypeScript type inference works well when using Hook. Which means you have nothing to worry about. For example:

/ / `value` is inferred as a string / / `setValue` is inferred as (newValue: string) = > void const [value, setValue] = useState ('')

TypeScript infers the value given by the useState hook. This is the result of a collaborative work of React and TypeScript.

In rare cases, you need to initialize Hook with a null value, and you can use generics and pass a union to type Hook correctly. View this instance:

Type User = {email: string; id: string;} / / the generic is the

< >

/ / the union is the User | null / / together, TypeScript knows, "Ah, user can be User or null". Const [user, setUser] = useState (null)

Here is an example of using userReducer:

Type AppState = {}; type Action = | {type: "SET_ONE"; payload: string} | {type: "SET_TWO"; payload: number}; export function reducer (state: AppState, action: Action): AppState {switch (action.type) {case "SET_ONE": return {... state, one: action.payload / / `payload` is string} Case "SET_TWO": return {... state, two: action.payload / / `payload` is number}; default: return state;}}

As you can see, Hooks doesn't add much complexity to React and TypeScript projects.

Common use cases

This section describes some common pitfalls when people use TypeScript with React. We hope that by sharing this knowledge, you can avoid trampling on it and even share it with others.

Handling form events

One of the most common situations is when onChange types correctly on the input field of the form. This is an example:

Import React from 'react' const MyInput = () = > {const [value, setValue] = React.useState ('') / / event type is "ChangeEvent" / / We pass "HTMLInputElement" to input function onChange (e: React.ChangeEvent) {setValue (e.target.value)} return}

Extend the Props of a component

Sometimes you want to take the Props declared for one component and extend them to use them on another. But you may want to modify one or two properties. Remember how we looked at two types of components: Props, type, or interfaces? Depending on which component you use determines how you extend the component Props. Let's first look at how to use type:

Import React from 'react'; type ButtonProps = {/ * * the background color of the button * / color: string; / * * the text to show inside the button * / text: string;} type ContainerProps = ButtonProps & {/ * * the height of the container (value used with' px') * / height: number;} const Container: React.FC = ({color, height, width, text}) = > {return {text}}

If you use interface to declare props, then we can essentially "extend" the interface using the keyword extends, with some modifications:

Import React from 'react'; interface ButtonProps {/ * * the background color of the button * / color: string; / * * the text to show inside the button * / text: string;} interface ContainerProps extends ButtonProps {/ * * the height of the container (value used with' px') * / height: number;} const Container: React.FC = ({color, height, width, text}) = > {return {text}}

Both methods can solve the problem. It's up to you to decide which one to use. Personally, extending interface is more readable, but ultimately it's up to you and your team.

Third-party library

Whether for GraphQL clients such as Apollo or for testing such as React Testing Library, we often use third-party libraries in React and TypeScript projects. When this happens, the first thing you need to do is to see if the library has a package with TypeScript type definition @ types. You can run:

# yarn yarn add @ types/ # npm npm install @ types/

For example, if you are using Jest, you can do this by running the following command:

# yarn yarn add @ types/jest # npm npm install @ types/jest

This allows you to increase type safety whenever you use Jest in your project.

The @ types namespace is reserved for package type definition. They are located in a repository called DefinitelyTyped, which is jointly maintained by the TypeScript team and the community.

This is the end of "how to write React in TypeScript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report